Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
In non-DEBUG mode the linelog.debug("Request body: {}", new String(body, "UTF-8"));instead oflog.debug(MessageFormatter.format("Request body: {}", new String(body, "UTF-8")));avoids the creation of the string that is created viaMessageFormatter.format(String messagePattern, Object arg), but not the creation of the other string that is created bynew String(body, "UTF-8").This means it isnot a false positive, because the arguments are calculated first before the logging method is called.As long asSLF4J does not support lambda expression to lazy evaluate arguments, the following utility method can be used as a workaround:private static Object lazyToString(final Supplier<String> stringSupplier) { return new Object() { @Override public String toString() { return stringSupplier.get(); } }; }This can be used to limit the converting of the byte array into a string to the DEBUG mode only:log.debug("Request body: {}", lazyToString(() -> new String(body, StandardCharsets.UTF_8)));ShareFolloweditedApr 27, 2022 at 8:01walen7,18222 gold badges3838 silver badges6060 bronze badgesansweredOct 28, 2018 at 14:49howlgerhowlger32.3k1111 gold badges6262 silver badges103103 bronze badges0Add a comment|
I'm using latest Eclipse and Sonar pluginInanswerfor logging there's the following line:log.debug("Request body: {}", new String(body, "UTF-8"));Which should create String only if in DEBUG level:/** * Log a message at the DEBUG level according to the specified format * and argument. * <p/> * <p>This form avoids superfluous object creation when the logger * is disabled for the DEBUG level. </p> * * @param format the format string * @param arg the argument */ public void debug(String format, Object arg);But Sonar is marking it assquid:S2629:"Preconditions" and logging arguments should not require evaluation (squid:S2629)And give examples with concatenationlogger.log(Level.DEBUG, "Something went wrong: " + message); // Noncompliant; string concatenation performed even when log level too high to show DEBUG messagesIs it a false positive sonar warning or am I missing something?This isn't a duplicate ofthis questionwhich is generally asking about the rule concept, which is concatenation, but not formatting with creating object asnew StringAlsolinkof an answer says creatingnew Date()isn't creating an issue with built in format:public static void main(String[] args) { LOGGER.info("The program started at {}", new Date()); } }Logging this way, you avoid performance overhead for strings concatenation when nothing should be actually logged.
Eclipse - Sonar S2629 possible false positive with new String
You can use SonarLint to run the analysis before the commit. It can be installed as plugin into your editor. Download and further instructions are available herehttp://www.sonarlint.orgShareFolloweditedNov 1, 2021 at 7:49answeredNov 2, 2016 at 8:59Tibor BlenessyTibor Blenessy4,3123030 silver badges3737 bronze badges2The link now takes to 404. Seems like the CLI support for Sonarlint is discontinued -stackoverflow.com/questions/46975487/…–Vimal MaheedharanOct 29, 2021 at 3:331indeed @VimalMaheedharan , I updated my answer–Tibor BlenessyNov 1, 2021 at 7:49Add a comment|
I foundUsing SonarQube in Eclipseand will ask a separate question targeted at Python. But here I want to ask more generally how to use SonarQube as a replacement for lint-like UNIX CLI tools while I'm working on individual source filesbeforeI commit. Specifically, what if I don't want to fire up Eclipse? I just want to make some tweaks to source file and check it against rules such as "Collapsible 'if' statements should be merged" (the actual example that's blocking me today).Even if I could commit to an experimental branch and see my analysis before I open a pull request, that would be better than nothing.
How can I use SonarQube before making a commit?
In yoursonar-project.properties, you have two ways to ignore files:sonar.exclusions=the/full/path/*.xmlwill ignore all.xmlfiles inpath.sonar.exclusions=**/*.xmlwill ignore all.xmlfiles in the folder and sub-folders where you are.Here are the different wildcards:* zero or more characters ** zero or more directories ? a single characterYou can find more information onSonar DocumentationShareFolloweditedDec 15, 2016 at 10:24janos123k3030 gold badges234234 silver badges241241 bronze badgesansweredAug 4, 2014 at 6:15Jean-Baptiste MartinJean-Baptiste Martin85199 silver badges3131 bronze badgesAdd a comment|
This question already has an answer here:SonarQube - Using wildcards to ignore all xml files(1 answer)Closed6 years ago.We are using SonarQube version 4.3.2 with our Java project. We want to exclude all javascript files which are currently being analyzed. We tried excluding by using *.js in exclusion list, but it did not work. Please help.
SonarQube 4.3.2 Javascript exclude [duplicate]
I had the same issue using v.5.7.2. There's a still opendiscussion on GitHubabout that topic. It seems when callingdotnet installit will implcitely also calldotnet restore, which will use yourNuget.config. When there's a private feed that needs authentication within that file,dotnet installwill fail instead of just using the next feed available. So we can add the official nuget-feed and ignore any others using the following:dotnet tool install --global dotnet-sonarscanner --add-source 'https://api.nuget.org/v3/index.json' --ignore-failed-sourcesThis will still issue a warning because the private feed cannot be accessed. However it will process further and you can use the tool.ShareFollowansweredAug 5, 2022 at 12:55MakePeaceGreatAgainMakePeaceGreatAgain36.1k66 gold badges6161 silver badges114114 bronze badges1I was with this problem to install wix package. And this answer helped me. dotnet tool install wix -g --add-source 'api.nuget.org/v3/index.json' --ignore-failed-sources–Fabrício PereiraMay 25, 2023 at 13:27Add a comment|
Just trying to install Sonarqube without docker image, locally:-- dotnet tool install --global dotnet-sonarscanner C:\Program Files\dotnet\sdk\6.0.200\NuGet.targets(130,5): error : Unable to load the service index for sourcehttps://pkgs.dev.azure.com/tPointAgileOrg/tPoint/_packaging/tPoint/nuget/v3/index.json. [C:\Users\Anri_Kezeroti\AppData\Local\Temp\utymnwsa.3vd\restore.csproj] C:\Program Files\dotnet\sdk\6.0.200\NuGet.targets(130,5): error : Response status code does not indicate success: 401 (Unauthorized). [C:\Users\Anri_Kezeroti\AppData\Local\Temp\utymnwsa.3vd\restore.csproj]The tool package could not be restored. Tool 'dotnet-sonarscanner' failed to install. This failure may have been caused by:You are attempting to install a preview release and did not use the --version option to specify the version.A package by this name was found, but it was not a .NET tool.The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.You mistyped the name of the tool.For more reasons, including package naming enforcement, visithttps://aka.ms/failure-installing-tool
Error dotnet tool install --global dotnet-sonarscanner
understood my error, with slf4j logger, {} needs to be used instead of {0}ShareFollowansweredApr 25, 2018 at 12:01Aurélien PupierAurélien Pupier74411 gold badge99 silver badges2323 bronze badgesAdd a comment|
it seems that a new rule is available with latest version. I have several issue reported as "Printf-style format strings should be used correctly (squid:S3457)"I don't understand the description and what is wrong inmy case:LOGGER.info("Checking for client process pid: {0}", parentProcessId); // issue: String contains no format specifiersIn the rules description we have:java.util.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {0}.", myObject.toString()); // Noncompliant; no need to call toString() on objects logger.log(java.util.logging.Level.SEVERE, "Result.", new Exception()); // compliant, parameter is an exception logger.log(java.util.logging.Level.SEVERE, "Result '{0}'", 14); // Noncompliant {{String contains no format specifiers.}}andjava.util.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {0}.", myObject); logger.log(java.util.logging.Level.SEVERE, "Result {0}'", 14);What's the difference with my cases? Can you help me understand what is the correct way to write it?
[Sonarqube][Java]Printf-style format strings should be used correctly
I confirm SonarSource (SonarQube, SonarCloud, SonarLint) doesn't provide yet any feature to scan IaC files (Terraform, CloudFormation, ...). This is part of our 2021 roadmap to bring features to secure Cloud Native apps which include to raise issues on your IaC files. The work just started on our side, so don't expect this to come soon but more starting from Q3.Edit 2022-01: SonarQube and SonarCloud now support analysis of CloudFormation and Terraform for AWS + Azure (GPC is coming in Q1 2022). See the announcements for details:https://www.sonarqube.org/sonarqube-9-2/https://www.sonarqube.org/sonarqube-9-3/ShareFolloweditedFeb 2, 2022 at 14:32CommunityBot111 silver badgeansweredApr 23, 2021 at 6:43Alexandre - SonarSourceAlexandre - SonarSource51922 silver badges55 bronze badges13Where are the doc!? I can't find anything explaining how to actually use sonarcloud to scan terraform files. Do I just create a new project and it reads the source code automatically?–red888Mar 15, 2022 at 16:21Add a comment|
Can we use SonarQube to scan Terraform code (to create Azure infrastructure such as RBAC, PIM, allowed locations etc) for error and vulnerabilities with Azure DevOps CI/CD pipelines?I found some link but not sure?https://registry.terraform.io/providers/jdamata/sonarqube/latest/docs/resources/sonarqube_qualitygate_project_association
Can we use SonarQube to scan Terraform scripts with Azure DevOps CI/CD pipeline?
I've just had the same issue.Usingprettier-ignoreworked for me :// prettier-ignore export const overviewReducer = (state = initialState, action) => { //NOSONARNot the best solution, but at least it solves the problem.ShareFollowansweredJan 2, 2020 at 13:25c4kc4k4,31955 gold badges4242 silver badges6868 bronze badgesAdd a comment|
Havingeditor.formatOnSave = truein VS code, when trying to ignore some rules and suppress the error using //NOSONAR at the end of the line. The line comment is going down. How and where these rules can be configured?export const overviewReducer = (state = initialState, action) => { //NOSONARcoming to the next line like:export const overviewReducer = (state = initialState, action) => {//NOSONAR
How to use NOSONAR at the end of the line having ESLINT and Prettier configured?
We had the same problem. At first we used the above solution but after searching in the sonar code on github found the place where this setting should be placed:Edit the sonar.properties file and change the line:#sonar.search.javaAdditionalOpts=tosonar.search.javaAdditionalOpts=-Dbootstrap.system_call_filter=falseShareFollowansweredDec 12, 2017 at 20:58kdeenkhoornkdeenkhoorn9122 bronze badges2It's the correct way to start SonarQube where seccomp has not been compiled into kernel.–Eric HartmannDec 20, 2017 at 13:581If it helps, it's on inside folder <sonarqube-6.7>/conf folder and on line 215.–Vighnesh PaiJan 27, 2018 at 9:03Add a comment|
I've just upgraded SonarQube from 6.0 to 6.7 LTS running in a CentOS 6 box, and noticed that ElasticSearch (ES) failed to start because the kernel (2.6.32-696.3.1.el6.x86_64) doesn't haveseccompavailable.This is officially documented atSystem call filter checkand a correct workaround for systems without this feature is to configurebootstrap.system_call_filterto false inelasticsearch.yml.The issue here is because Sonar creates the ES configuration at startup, writing in$SONAR_HOME/temp/conf/es/elasticsearch.ymland I haven't found a way to setbootstrap.system_call_filterproperty.I tried a natural (undocumented) way introducingsonar.search.bootstrap.system_call_filterandbootstrap.system_call_filterproperties insonar.propertiesbut it doesn't work.
SonarQube 6.7 failed to start because CONFIG_SECCOMP not compiled into kernel
If you look at the description of ruleRSPEC-1166, especially the title:Exception handlers should preserve theoriginal exceptionIn your case you are only taking care of themessageof the exception, thus not preserving the originalexception (including itsstacktrace). Thus your resulting logs will hide the root cause of the failure.This rule detects that you are not using the caught exception as an entire object in the catch block.Suitable fixesThis might not be suitable in your case:either mark the rule as "won't fix"or deactivate the rule in your quality profileShareFolloweditedJan 6, 2022 at 20:23hc_dev8,74611 gold badge2828 silver badges4040 bronze badgesansweredAug 25, 2015 at 7:09benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges4Thanks for you info, however I am still confuse. If you look atNoncompliant code example, second sample,try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); }looks like mine. Isn't it?–HesamAug 25, 2015 at 7:311yes, and this is considered as _NON_compliant so this is expected isn't it ?–benzonicoAug 25, 2015 at 7:43Yup, thanks. I got headache for spending time on this.... You are absolutely right.–HesamAug 25, 2015 at 7:52Excellent explanation with link and fixes which deserved a hopefully improving edit. I justanswered related question with RSPEC-2139maybe you like to "improve back" 😊️–hc_devJan 6, 2022 at 20:32Add a comment|
Possible duplicate ofSonar complaining about logging and rethrowing the exception.This is my code in a class:try { this.processDeepLinkData(data); } catch (final Exception e) { // Error while parsing data // Nothing we can do Logger.error(TAG, "Exception thrown on processDeepLinkData. Msg: " + e.getMessage()); }and my Logger class:import android.content.Context; import android.util.Log; import com.crashlytics.android.Crashlytics; public final class Logger { /** * Convenience method. * * @see Logger#log(String, String) */ public static void error(final String tag, final String msg) { if (Logger.DEBUG) { Log.e(tag, "" + msg); } else { Logger.log(tag, "" + msg); } } private static void log(final String tag, final String msg) { Crashlytics.log(tag + ": " + msg); } }Sonar is pointing tocatch (final Exception e)and saysEither log or rethrow this exception. What do you think?
Either log or rethrow this exception
Yes, you need first to pull your project from GitHub, and then launch a Sonar analysis on your local copy (Sonar needs the file to exist on the file system to be able to analyse them).So you can pull your project manually or obvioulsy using a CI server like Jenkins/Hudson.ShareFollowansweredJan 28, 2013 at 10:34Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges4can we done it without using hudson? if yes how we can do it, am really unaware about this.–pbhleJan 28, 2013 at 10:521You can write you own script that does "git pull + mvn sonar:sonar", and schedule that script using the cron table (Unix/Linux) or the task scheduler (Windows). However, I'd advise you to prefer Hudson/Jenkins, those are far more powerful.–Fabrice - SonarSource TeamJan 28, 2013 at 11:00ok... thanks, means I just need to install the sonar plugin on hudson and configure a job over there. am i right?–pbhleJan 28, 2013 at 11:01Yes, see the documentation here:docs.codehaus.org/pages/viewpage.action?pageId=116359341(and please validate this answer if that answered your question!)–Fabrice - SonarSource TeamJan 28, 2013 at 11:15Add a comment|
I want to enable sonar with git but is it neccesary that first pull the project from git repository using hudson or something else and then sonar will analyse the code periodically on hudson .am I right means my steps :1.Pull project from git using hudson.2.Sonar on hudson will analyse the code and send the updates.?or directly we can use git+sonar how it works ,can anybody guide me to get it work.
sonar+github integration
I resolved this issue by deleting the entire.sonarqubefolder.ShareFolloweditedJul 6, 2020 at 11:41Cody Gray - on strike♦242k5050 gold badges496496 silver badges575575 bronze badgesansweredJul 6, 2020 at 10:19Rohan MohapatraRohan Mohapatra10111 silver badge44 bronze badges3I emptied the.sonarqubefolder in 2 places: Under my application project folder and under the%temp%folder. That worked for me.–Lee GrissomAug 16, 2021 at 1:11This helped in a CI/CD pipeline–tinoneticJun 28, 2022 at 12:12This worked for me: I removed .sonarqube folder in my user:C:\Users\MyUserName\.sonarqubeand also removeC:\Users\MyUserName\AppData\Local\Temp–satellite satelliteApr 11, 2023 at 16:11Add a comment|
I'm having random problems during my build process in TeamCity. I've got two configurations: First for Rebuild + Unit test. Second as artifact dependency, with SonarQube analyzer. When Teamcity is executing first configuration, I'm receiving random error messages every 5-10 builds:CSC error CS0006: Metadata file 'E:\TeamCity\buildAgent2\temp\buildTmp\.sonarqube\resources\0\Google.Protobuf.dll' could not be foundCSC error CS0006: Metadata file 'E:\TeamCity\buildAgent2\temp\buildTmp\.sonarqube\resources\0\SonarAnalyzer.CSharp.dll' could not be foundCSC error CS0006: Metadata file 'E:\TeamCity\buildAgent2\temp\buildTmp\.sonarqube\resources\0\SonarAnalyzer.dll' could not be foundErrors are totally random - when I run process one more time without any changes, error is gone. When I check buildTmp\.sonarqube directory, there is nothing there, no matter if build was successful or not.I don't have any references in my project to those libraries and my Rebuild step has nothing to do with SonarQube. We are using SonarLint in VisualStudio 2017, but once again, we don't have any references to SonarQube in our *.csproj files.
CSC error CS0006: Metadata file 'SonarAnalyzer.dll' could not be found
Aren't they quite the same ?Not at all.Fromhttp://www.jacoco.org/jacoco/trunk/doc/counters.html:The smallest unit JaCoCo counts are single Javabyte codeinstructions.comparison of "instructions" with "lines of code" is like comparison of apples and oranges - they don't represent the same thing. Single line of code usually contains many bytecode instructions.For exampleSystem.out.println("Hello, World!");is a single line, but 3 bytecode instructions as can be seen usingjavap(Java Class File Disassembler):0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #3 // String Hello, World! 5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)VBTW JaCoCo also counts lines. But while comparing this one with LoC in SonarQube, please take into account that algorithms of calculation are different - JaCoCo computes this number by analyzing information recorded by compiler in bytecode, while SonarQube computes this number by analyzing source code.ShareFolloweditedMar 30, 2018 at 11:27answeredMar 30, 2018 at 10:31GodinGodin10.1k33 gold badges4141 silver badges7878 bronze badges0Add a comment|
I have a projet composed of numerous modules. I am running bothJaCoCofor unit tests coverage andSonarfor code quality.For a technical reason, I can't use JaCoCo reports for one of my modules (GWT erases thetargetfolder and I couldn't go past this issue yet).Let's say I have 8 modules, from 1 to 8. One of them is for domain objects only, so I don't want to cover it with my tests. Same goes for another one, dedicated for auto-generated classes.JaCoCo runs on 5 modules, and Sonar on 6 modules.The total instructions shown by JaCoCo is 145k.Sonar shows a total of 75k LOC.Aren't theyquitethe same ? Did I miss something ? Is JaCoCo taking in account the whole project whatever reports I feed him ? What can possibly explain this gap in measurement ?
Lines of Code VS Instructions while measuring code quality
The default values aresonar/sonar.Edit: this was answered at the time of SonarQube 5.6.x. Recent versions (e.g. v6.7 LTS) might have changed to empty username/password (for embedded database).ShareFolloweditedApr 11, 2018 at 13:09answeredAug 29, 2016 at 13:15Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badges3Doesn't work for me, I use sonarqube 6.7.3. Says Wrong user name or password [28000-176] 28000/28000–Karthick Meenakshi SundaramApr 10, 2018 at 16:181What worked for me was an empty username and an empty password! :-)–Karthick Meenakshi SundaramApr 10, 2018 at 16:35Thanks, answer fine-tuned accordingly–Nicolas B.Apr 11, 2018 at 13:09Add a comment|
I'm running SonarQube 5.6.1 and am trying to save a view that I created. To do that, I want to take a peek at H2 DB that Sonar (according to it's own readme) uses for internal embedded DB.I've ran the H2 jar file and in console was able to log in to dummy DB. If SonarQUbe is running, I can't connect.So, what are default credentials for that DB? Tried my user credentials and admin/admin, none work. Admin/admin is default for SonarQube administrator user.
SonarQube default credentials for internal H2 db?
I believe you first ran\windows-x86-64\InstallNTService.batsuccessfully and thenStartSonar.batunsuccessfully (the inverse order of what you describe).You probably have [this problem]:http://qualilogy.com/fr/wp-content/uploads/sites/2/2013/09/Sonar_ServiceLaunchError2.jpgWindows could not start the Sonar service on Local Computer.Error 1067: The process terminated unexpectedly.In that case, the solution is to change the user/rights to launch the Sonar service:https://qualilogy.com/en/migrate-sonarqube-tomcat-to-windows-service/Go to the Services window, find the Sonar service, and open the Properties windows to change the user it logs on as to one with sufficient permissions.ShareFolloweditedFeb 6, 2023 at 16:45TylerH21k7070 gold badges7878 silver badges104104 bronze badgesansweredSep 11, 2014 at 8:47QualilogyQualilogy78955 silver badges66 bronze badges0Add a comment|
I'm installing sonarqube on Windows Server 2012.I have followed the following steps:Downloaded sonarqube4.4 and extracted to C:\SonarqubeDownloaded Java JDK 1.7.0_60 and jre 1.7.0_67 as well as jre7Installed Windows SDK 7 and .NET Framework 4Navigated to C:\sonar\bin\windows x86-64 and ran StartSonar.bat as an administrator, this ran ok with no output and Ihad to hot ctrl- Z to breakI then ran \windows-x86-64\InstallNTService.bat as an administrator and I am seeing the sonarQube services was launched, but failed to start.Not sure what the problem is.
SonarQube installation failing to start service
see the pmd explanation for this:http://qa.nuiton.org/sonar/rules/show/pmd:CollapsibleIfStatements?layout=falsePMD/Sonar identified, that you don't need 2 if statements, but can rather combine it to one using AND/OR opeartors.this should be OK:if (getSomething().equals(getSomething()) && getsomehing.contains(getSomething())) { }ShareFollowansweredAug 22, 2012 at 7:04Peter ButkovicPeter Butkovic11.6k1010 gold badges5757 silver badges8383 bronze badgesAdd a comment|
I am getting the exception "collapsible if statement".Through the sonar in the following code.if(getSomething().equals(getSomething()){ if(getsomehing.contains(getSomething()){ } }Collapsible if statements These statements could be combined.What is the meaning of this metric?
sonar-collapsible if statements
After digging around and trying several solutions, I finally solved this. What happened was that I initially installedFastlanewith this command:brew cask install FastlaneAnd it seems that it was using another version of ruby while I had a newer one. So I uninstalled it with:brew cask uninstall FastlaneAnd then I re-installed it with this command:sudo gem install -n /usr/local/bin fastlane -NVBecause I was having problems with permissions and then all worked good.References and other solutions:Github threadusr/local/binShareFolloweditedMay 29, 2020 at 19:33answeredNov 9, 2019 at 5:07NicolasElPapuNicolasElPapu1,62222 gold badges1111 silver badges2626 bronze badges13Author of the linked article here. Thanks for reading it, trying it, and sharing the issue and resolution for the greater good of the community.–NishNov 28, 2019 at 16:23Add a comment|
I finished this tutorial on Medium in order to integrate my Xcode project withSonarQubeto have some metrics.Setup SonarQube - Swift. I was able to make it through the last step that is: runningfastlane metricson the terminal while being in the root of the project directory. But I get this error on step "slather".nokogiri requires Ruby version >= 2.3.0., fastlane finished with errors:I have also found that someone had a similar question here, but no answers:Similar QuestionIf I run:nicolas$ ruby --versionI get ruby version2.6.3, which is higher than the required2.3ruby 2.6.3p62 (2019-04-16 revision 67580) [universal.x86_64-darwin19]Does anyone knows how to fix this, or got any hunches? Thanks in advance, I appreciate any help.
Fastlane "nokogiri requires Ruby version >= 2.3.0." Error
we did have the same issue within our project, and sonar allows you to define exclusions for rules and files inAdministration -> Congifuration -> Analysis Scope.you will find there a section calledIgnore issues on Multiple Criteriaand there you can enter the rule and a "file pattern" to exclude files from this rule.like:ShareFollowansweredDec 5, 2018 at 19:23Simon SchrottnerSimon Schrottner4,42611 gold badge2525 silver badges3939 bronze badgesAdd a comment|
I am using combineReducer to combine reducers and reducer like thisconst todo = (state = {}, action) => { switch (action.type) { //... case 'TOGGLE_TODO': if (state.id !== action.id) { return state } return Object.assign({}, state, { completed: !state.completed }) default: return state } }My problem is if i am defining reducer like that i am getting sonar code smellFunction parameters with default values should be last1but combine reducer pass argument in this sequence only how to work on this?
sonar code smell for reducer used in combineReducer
Each rule that detects an issue in SonarQube has a remediation effort function. This remediation function is visible on the description page of each rule:This remediation effort is used to compute the technical debt of every code smell (= maintainability issues).The technical debt of a project is the simply the sum of the technical debt of every code smell in the project (which means that bugs and vulnerabilities don't contribute to the technical debt).ShareFollowansweredMar 9, 2018 at 7:51Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges1In an older version (or maybe it was a plugin...), technical debt was a function of the time to fix issues as you describe, but also a function of test coverage and duplication. There was even a pie graph showing how these factors would influence the debt. So,test coverageandduplicationare not part of the technical debt calculation anymore?–Paulo MersonAug 9, 2019 at 16:38Add a comment|
In the new version of sonarqube, the documntation states that technical debt (TD)TD= Effort to fix all maintainability issues. The measure is stored in minutes in the DB. An 8-hour day is assumed when values are shown in days.However, how does sonarqube measure maintainability issues?
How does sonarQube calculate technical debt
The SonarQube Scanners don't run in isolation to analyze your code. They interact with a SonarQube server, and language analyzers loaded in that server.Torun an initial trial,download the latest version from sonarqube.org, expand the resulting zip, and start the server.Thenyou'll be able to successfully run a scan.Note that the instructions I've just given you start the server with a for-trial-only on-board H2 database. Youshould notgo into production with that database.ShareFollowansweredJun 2, 2017 at 13:01G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badgesAdd a comment|
When I build my maven project locally, I run a sonar check. I am getting the following error. Googling hasn't resolved the issue.I am new to SonarQube - am I missing config?[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.3.0.603:sonar (default-cli) on project x: Unable to execute SonarQube: Fail to get bootstrap index from server: Failed to connect to localhost/0:0:0:0:0:0:0:1:9000: Connection refused: connect
SonarQube - Failed to connect to > localhost/0:0:0:0:0:0:0:1:9000
You should find that setting in Sonarqube, not in Jenkins. Check here:ShareFollowansweredNov 19, 2014 at 22:22carlo.bongiovannicarlo.bongiovanni14166 bronze badges2thanks @carlo for pointing me in correct direction, Would you please let me know what would be the possible reason of this issue as only increasing default time not working for me.–AmitNov 20, 2014 at 10:10I have the same problem. Were you able to resolve @Amit ? I've increased the timeout to 3600000 ms, which is 1 hour and I keep seeing the below message.. <br> 01:48:45.618 [WARNING] [JOURNAL_FLUSHER] WARNING Journal flush operation took 126,162ms last 8 cycles average is 72,125ms <br> Any pointers?–Karthick Meenakshi SundaramApr 24, 2018 at 10:51Add a comment|
While running sonar from jenkins job for one of my project I am facing issue ," Can not execute SonarQube analysis: Can not execute Findbugs with a timeout threshold value of 1200000 milliseconds: TimeoutException -> [Help 1]"I tried to google it for help but every where I found only solution ."You can increase the timeout: Settings > General Settings > Java > Findbugs > sonar.findbugs.timeout"In my office jenkins installed as a service and I am not able to find the above mention path, Any one would please give any details what would be the possible cause of this issue. What could be the solution and if the solution is like above which I mention then please guide me where I can find path or please let me know that if I need to update any config file.
Jenkins findbug threshold issue
This is no longer supported as of 4.0.End of Support of WAR deployment ModeThe standalone mode is now the only mode that is supported. Standalone mode embeds a Tomcat server.http://docs.sonarqube.org/display/SONAR/Release+4.0+Upgrade+NotesShareFolloweditedMar 4, 2015 at 16:08schnatterer7,64977 gold badges6363 silver badges8181 bronze badgesansweredJan 17, 2014 at 17:57CTarczonCTarczon89899 silver badges1919 bronze badges4On which port start this sonar-tomcat?–MAGx2Jan 17, 2014 at 22:39OK I found it. Just edit lines: # TCP port for incoming HTTP connections. Disabled when value is -1. sonar.web.port=9999–MAGx2Jan 17, 2014 at 22:451Is it maybe still possible to build the war file for Version 4.4.5 on my own?–kiltekAug 28, 2015 at 14:28Running embedded tomcat is a waste of resources–nikenAug 23, 2016 at 14:04Add a comment|
How can I run Sonar on my Unix system with Tomcat. In previous versions there was way to make .war and deploy it on Tomcat.I tried to put into folder webaps (Tomcat) and run scriptsonarqube-4.1\bin\solaris-x86-32\sonar.sh. Everything was OK, but I didn't know what to write in webbrowser to get to Sonar.Version of my OS: *SunOS mdjava0.mydevil.net 5.11 joyent_20131213T023304Z i86pc i386 i86pc Solaris*
How to run Sonar 4.1 on Tomcat
I am the founder of the Checkstyle project. As far as I know, no such Checkstyle rules file exists. I am not surprised as Checkstyle checks can only check source code level things, such as Javadoc comments, whitespace, etc.Unlike FindBugs, Checkstyle does notcompilethe source code, and hence does not have access to type information which would be required to implement implement some of the recommendations made by Joshua Bloch in his Effective Java book.ShareFollowansweredFeb 14, 2011 at 3:23OliverOliver63955 silver badges99 bronze badges12nice to have you on StackOverflow. Thanks for the info. I appreciate it.–CoolBeansFeb 14, 2011 at 3:34Add a comment|
Does anyone know if there is a compilation of check style rules that covers most of the recommendations made by Joshua Bloch in his Effective Java book? I know I can add custom rules in the checkstyle plugin but I was wondering if anyone has already done so and if willing to share them. :)
checkstyle rules that covers Effective Java recommendations
LombokjavadocsaysNB: As of v1.16.2 which introduces this annotation, lombok doesn't actually add this annotation; we're setting it up so that lombok jars in widespread use start having this, which will make it easier to actually apply it later on.So try to update your lombok version. I have 1.18.2 and it works.ShareFolloweditedOct 9, 2018 at 15:02answeredOct 9, 2018 at 14:56Alexander PankinAlexander Pankin3,84711 gold badge1414 silver badges2525 bronze badges0Add a comment|
I'm trying to ignore lombok annotations in my Java project when using the code coverage tool "Sonarqube", I researched a lot about this and I ended adding this property to the "lombok.config" file:lombok.addLombokGeneratedAnnotation = trueBut when I execute "mvn test" or the "Run with coverage" option in IntelliJ I got this error in the console:Unknown key 'lombok.addLombokGeneratedAnnotation' (C:\Projects\...\lombok.config:3)And of course the generated coverage test still isn't ignore the lombok annotations, I'm using 0.8.1 version of Jacoco and 1.16.2 version of lombok.Any idea how to make this work?
Not able to ignore lombok annotations - Sonarqube
Stop thinking in term of language, since this is a blur concept in SonarQube. Just exclude the files you don't want to analyze, using for example the propertysonar.exclusions.For example, when considering a pom.xml file, the "language" was historically XML (and rules provided by SonarXML). But we now also have rules provided by SonarJava.ShareFollowansweredOct 11, 2017 at 12:31Julien H. - SonarSource TeamJulien H. - SonarSource Team5,25711 gold badge2020 silver badges2525 bronze badgesAdd a comment|
Sonar scanner runs analysis for all the available plugins installed in SonarQube. But for some of the projects analysis should be run only for some languages(For example Java and Javascript).sonar.languageparameter allows me to set only one language. Is there any way to set multiple languages for analysis.
Run analysis for a project only with a set of specified languages
The false positive is related to an imperfection in our dataflow analysis engine - it does not take into account the casts between floating point and integer numbers (yet) and cannot recognize when a floating point number has been truncated.I will try to elaborate a bit: the dataflow analysis engine tracks the values of the local variables in the analyzed methods, and when a new value is being assigned to a variable, the engine creates a special object that represents the actual value. When you assign one variable to another variable, that object remains the same. For example:var x = 5; // the symbol of x is associated with value_0 var y = x; // the symbol of y is associated with value_0 if (x == y) // value_0 is compared with value_0 --> always trueThe values we assign do not contain type information (yet) and we cannot detect (yet) changes in cases like yours:var x = 5.5; // the symbol of x is associated with value_0 var y = (int)x; // the symbol of y is associated with value_0 (wrong) if (x == y) // false positiveand we generate false positives, but they are relatively rare, because most casts do not generate new values.Thanks for the feedback, we will be looking into thatin the near future.ShareFollowansweredSep 1, 2017 at 11:34ValVal2,03011 gold badge1212 silver badges1616 bronze badgesAdd a comment|
Why is SonarQube complaining about this part of the code?I checked this code and not always this value is true.public static void WriteJson(object value) { decimal decimalValue = ((decimal?)value).Value; int intValue = (int)decimalValue; if (decimalValue == intValue) Console.WriteLine(intValue); else Console.WriteLine(decimalValue); Console.ReadKey(); }Why is SonarQube complaining about this?
Change this condition so that it does not always evaluate to 'true'
That's aknown bugin the SonarQube JavaScript analyser which was fixed a few months ago. You should upgrade to the latest version of the JavaScript plugin.ShareFollowansweredNov 3, 2016 at 7:40Pierre-YvesPierre-Yves1,5061111 silver badges1616 bronze badgesAdd a comment|
This is my code:const a = function(obj) { for (let key in obj) { if (!obj.hasOwnProperty(key)) { continue; } console.info(key.split('_')); } }; a({a_b: 123});I thought there is no problem at all but SonarQube gives me a critical error:TypeError can be thrown as "key" might be null or undefined here.The wordkeyinkey.split('_')is highlighted. Indicating variable key can be undefined/null here.I tried to pass in something like{[undefined]: 123}, and the variablekeybecomes a string "undefined" instead of real undefined.Hence. I am wondering will the key be undefined/null in any possible situation? Or is it just a False Positive?Here is a screenshot:
Can For-In loop result an undefined or null?
Yes it is possible...sonar.projectKey=project sonar.projectName=project sonar.projectVersion=1.0 sonar.branch=master sonar.sources=. sonar.language=php # Available modules sonar.modules=module1, module2 # Global source directory sonar.sources=. sonar.language=php # Module1 module1.sonar.projectName=Module1 module1.sonar.projectBaseDir=path/module1 module1.sonar.modules=subModule1 module1.subModule1.sonar.projectName=subModule1 module1.subModule1.projectBaseDir=path/subModule1 # Module2 module2.sonar.projectName=Module2 module2.sonar.projectBaseDir=path/module2ShareFollowansweredMar 4, 2016 at 9:49user3415653user341565333533 silver badges1414 bronze badges21That's the more compact method and probably the easier one to manage, but you can alsoput a properties file in each module–G. Ann - SonarSource TeamMar 4, 2016 at 12:331This link is no longer active.–OverMarsJan 28, 2021 at 22:59Add a comment|
Is it possible to define sub-modules on a module in the sonar-project.properties?My current config looks like this:sonar.projectKey=project sonar.projectName=project sonar.projectVersion=1.0 sonar.branch=master sonar.sources=. sonar.language=php # Available modules sonar.modules=module1, module2 # Global source directory sonar.sources=. sonar.language=php # Module1 module1.sonar.projectName=Module1 module1.sonar.projectBaseDir=path/module1 # Module2 module2.sonar.projectName=Module2 module2.sonar.projectBaseDir=path/module2But the module1 has also sub-modules.
Sonar project sub-modules
I'd say your choices are to extract a common ancestor class from Market and MarketDTO, or mark the duplicated blocks issues Won't Fix. (They'renotreally false positives, are they?)ShareFollowansweredFeb 5, 2016 at 12:39G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges4Thanks, both options sound acceptable for me. Just one more question, how SonarQube defines this rule on accessors? If two Java beans are totally irrelevant but only accidentally have 3 fields with same names (e.g. common ones like id, name etc.), are they still considered as duplication?–MichaelYuFeb 5, 2016 at 12:51It simply looks at the number of duplicate tokens in a row, and takes no notice whatsoever of semantics (how could it?)–G. Ann - SonarSource TeamFeb 5, 2016 at 12:521I guess so too. Then it is very likely say two classesPersonandMarketwhich both only have three fieldsid,name,status, are their accessors duplicated in the eyes of SonarQube? If they are not, then whyMarketandMarketDTOare? As @chrylis said, accessors may better be left out in duplication code scanning.–MichaelYuFeb 5, 2016 at 13:00If you want to discuss the philosophy of duplication detection, then you should open a thread on the Google group (groups.google.com/forum/#!forum/sonarqube)–G. Ann - SonarSource TeamFeb 5, 2016 at 13:43Add a comment|
There are two POJOsMarketandMarketDTOin two packages.Marketis a mapping object for JSON response from remote service.MarketDTOis a response object which will be exposed via our service.There are some data massage fromMarket->MarketDTO. They have some common fields and both have unique fields as well. There are 3 common fields such asid,nameandstatus.However, Sonarqube indicates their getters and setters asduplicated blocks of codes to be removed. Is this actually bad code or I should just mark it asfalse positive?
Sonarqube duplicated blocks of code between POJOs
As Sonarqube intends to provide the least possible configuration possible on rules: you should deactivate the rule with keysquid:LeftCurlyBraceEndLineCheckand I am guessing that you want to activate the rule :squid:LeftCurlyBraceStartLineCheckPlease note that those rules have nothing to do with Checkstyle.ShareFollowansweredMay 28, 2014 at 9:59benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges1Ohh. I didn't know that rule exists. Thanks!–yoyoMay 28, 2014 at 10:05Add a comment|
I wish to change the rule 'Left curly braces should be located at the end of lines of code' since we are using a different convention.Thanks in advance!
Can I edit some rules in SonarQube?
Instead of installing this plugin you can alos use directly inclusions or exclusion (or both).Within a executed pom.xml you can writepathToInclude(within the property section) and within the console you must add a property with-Dsonar.inclusions=pathToInclude-Dsonar.inclusions=file:/path_to_my_project/MyProject.java //only the file above will be analyzed -Dsonar.exclusions=file:/path_to_my_project_root/another_directory/**/* //all subfolders and files within "another_directory" are exclued / ignored. -Dsonar.inclusions=file:/path_to_my_project/another_directory/MyProject.java -Dsonar.exclusions=file:/path_to_my_project/another_directory/**/* //all subfolders and files within "another_directory" are exclued / ignored EXCEPT MyProject.java.ShareFollowansweredMay 8, 2014 at 10:01KrummyKrummy6581515 silver badges2424 bronze badgesAdd a comment|
My project is too big, and running Sonar on the entire project is taking lots of time and memory. So I want to know if there is any means to run sonar on a single java file.
Any means to run Sonar analysis on a single file?
Answers:If you do not set those 2 properties, you won't have test results ("sonar.tests") nor violations detected by Findbugs or bytecode-based tools ("sonar.binaries")."sonar.binaries" should contain only compiled sources, not testsNo. Only "sonar.libraries" can (and actually must) point to JAR files.ShareFollowansweredDec 10, 2012 at 8:28Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badgesAdd a comment|
In Sonar documentation there are two properties options, thesonar.testsandsonar.binaries.# path to test source directories (optional) sonar.tests=testDir1,testDir2 # path to project binaries (optional), for example directory of Java bytecode sonar.binaries=binDirQuestions:Ifsonar.testsandsonar.binariesare added to my Ant target, how do they show up in Sonar? What would be different in Sonar if I did/did not set these properties?Shouldsonar.binariescontain both source binaries and test binaries, or only source?Can .jar files be given to both properties instead of path to actual .class files and/or .java files?
Sonar tests and binaries properties, what do they do?
Ok, we've solved this to our satisfaction, though it did require a custom Sonar plugin.We created a version of BuildBreaker (which we called BuildWarner). The only difference (other than plugin name, package name, class name, etc) is line 44 of AlertThresholdChecker.java is changed from :fail("Alert thresholds have been hit (" + count + " times).");to :logger.info("SONARTHRESHOLDSEXCEEDED - Alert thresholds have been hit (" + count + " times).");Once this is running in Sonar, the Jenkins console will include the phraseSONARTHRESHOLDSEXCEEDEDif any alert hits reaches the Error Threshold level.Then, install the Jenkins Groovy Postbuild plugin. We use the following Groovy script :if(manager.logContains(".*SONARTHRESHOLDSEXCEEDED.*")) { manager.addWarningBadge("Sonar Thresholds Exceeded") manager.createSummary("warning.gif").appendText("<h1>Sonar Thresholds Exceeded</h1>", false, false, false, "red") manager.buildUnstable() }You can also use the Jenkins Text Finder plugin if you prefer.Important to note is that the Sonar plugin must be BEFORE the Groovy Post Build or Text Finder plugin.Hope this helps other people.ShareFollowansweredSep 21, 2012 at 16:03croverscrovers33944 silver badges1212 bronze badgesAdd a comment|
We're running Sonar from Jenkins and would like to mark the build as unstable when Sonar limits are exceeded. We've got the appropriate limits set as Alerts in the quality profile.We thought we could use Build Breaker to mark Sonar as failed (which puts that fact into the Jenkins log) and then use a Jenkins Post-build Groovy script to unstable the build in that case.Unfortunately, the Jenkins Sonar plugin marks the build failed (and stops the build process) if Sonar fails and the Jenkins folks have indicated that's as designed and have set the relevant defect to 'will not fix'.I've also tried setting Sonar's logging to Verbose hoping that the fact that the limits that were exceeded would be in the log (so we could again use a post build groovy task), but that doesn't seem to be the case either.Any insight? At this point, it appears to me that the best thing would be to create a variant of Build Breaker that simply reports that alerts but does not break the build, but I'd prefer not to go the custom plugin route if it can be avoided.
Making Jenkins Build unstable when Sonar limits exceeded
I would suggestcreating an architectural constraintwithin Sonar.The example demonstrates a rule banning the use of *java.sql.** classes.ShareFolloweditedSep 5, 2017 at 9:05bigbear300154699 silver badges2020 bronze badgesansweredJan 17, 2012 at 0:23Mark O'ConnorMark O'Connor76.6k1010 gold badges140140 silver badges186186 bronze badges1That is exactly what I was looking for. Somehow I overlooked that rule in Sonar. Thanks! Works like a champ.–jaycyn94Jan 17, 2012 at 16:26Add a comment|
Our team is looking to have better compliance with the OWASP guidelines, and one of the tasks is the prevention of SQL Injection attacks. In order to facilitate this, I was looking for a way to automatically check for the usage ofjava.sql.Statementin our codebase, so this could be flagged and changed to usePreparedStatement.Our build process is based on Maven and we also have Sonar setup to run analytics on the project. Some rules are already in place in Sonar to fail our builds if certain thresholds are met, so this could be implemented there. I have seen where I could setup a checkstyle regex rule looking for the import, but I wanted to see if there were other options as well.Any location along the development/build path would work. If there were something in intellij that would flag this, something in the maven build process, or a different way to flag this in Sonar, any of these would be fine.Thanks!!
Looking for a way to prevent to usage of java.sql.Statement in project
Pull request analysis cannot currently raisealltypes of issues. Specifically it cannot raise issues related to metrics because those are consolidated on the server side during analysis report processing and in a Pull Request analysis the analysis report is by design never submitted to the server.EDITThe PR analysis which is offered as part of the Developer Edition($)doesboth decorate the PR in the provider (e.g. GitHub)andshow the PR on the server. However, metric-related issuesstilldon't show up in this enhanced analysis.ShareFolloweditedAug 28, 2018 at 18:09answeredApr 21, 2017 at 16:35G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges3Hi, thanks for the answer! So currently I do not have a way to reflect in Github Pull Requests if the metric "Lines should have sufficient coverage by unit tests" fails?Or is there any other solution that Sonar offers so that I get a git commit status fail in Pull Requests if the new code that was added does not meet the coverage criteria in a Java project?–Marius IoanaApr 24, 2017 at 8:491Nope. That's a metric-related rule, so it can't raise issues during PR analysis.–G. Ann - SonarSource TeamApr 24, 2017 at 11:[email protected] Is that something supported in the Developer/Enterprise versions of SonarQube since it looks like it uses your branch analysis path for PRs?–dhermanJul 27, 2018 at 21:36Add a comment|
I have SonarQube server 5.6 and I am using Github. I have done the integration to setup Sonar Github plugin but I fail to understand whether this should report if the new code does not meet the code coverage threshold setup in the Quality Gate.In the Quality Gate I have defined an error to be raised unless there is more than 75% code coverage for the new code that is being introduced by a Pull Request.Should the Sonar Github plugin report an issue (comment) in Github pull request if the new code added does not meet the Quality Gate metric that I setup?Is there any way to mark in Github Pull Requests if the new code trying to be merged does not meet the coverage expectations?Thanks!
How to report code coverage in Github Pull Requests using Sonar Github plugin
MariaDB is not supported by SonarQube, seerequirements.ShareFollowansweredMay 24, 2016 at 12:59Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badges41i noticed the requirements, but API of mariadb10 is compatible with mysql 5.6, i have supposed the detection should be OK.–tgf2May 26, 2016 at 1:482Sounds like SonaQube should check MariaDB and update their detection code.–Rick JamesJun 1, 2016 at 17:23Can one of you confirm that this is still a problem in 2018?–Aiyion.PrimeFeb 7, 2018 at 17:024Yes. it is still a problem in 2018. Using MariaDB 10.2.12 on RHEL7 :2018.02.08 18:11:14 INFO web[][o.sonar.db.Database] Create JDBC data source for jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance 2018.02.08 18:11:14 ERROR web[][o.s.s.p.Platform] Web server startup failed: Unsupported mysql version: 5.5. Minimal supported version is 5.6.–user1669651Feb 8, 2018 at 18:13Add a comment|
I installed MariaDB with yum in CentOS 7.SonarQube throws this exception:org.sonar.api.utils.MessageException: Unsupported mysql version: 5.5. Minimal supported version is 5.6.When I reinstall MariaDB with version 10, SonarQube still throws the same exception.How does SonarQube-5.5 detect the MySQL version?The API of MariaDB 10 is compatible with MySQL 5.6 and CentOS 7 has replaced MySQL with MariaDB.Why does it not support MariaDB 10?
SonarQube cannot start with MariaDB 10
If you use Java 7+, there is a much simple way to use try-with-resources that is able to close resource itself and you needn't take care about that anymore. See try(PreparedStatement ps = connection.prepareStatement(DML)), a tutorial:https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.htmltry (PreparedStatement ps = connection.prepareStatement(DML)) { ps.setString(1, externalDeviceId); ps.setInt(2, internalDeviceId); ps.execute(); return ps.getUpdateCount() > 0; }ShareFollowansweredApr 12, 2016 at 13:55Martin StrejcMartin Strejc4,33722 gold badges2525 silver badges3939 bronze badgesAdd a comment|
In our code base we get Sonar reports violation for rule squid:S2095 on code like the following:PreparedStatement ps = null; try { ps = connection.prepareStatement(DML); ps.setString(1, externalDeviceId); ps.setInt(2, internalDeviceId); ps.execute(); return ps.getUpdateCount() > 0; } finally { Utilities.close(ps); }with Utilities.close implemented aspublic static final void close(final AutoCloseable ac) { if(ac != null) { try { ac.close(); } catch(Exception e) { } } }Is there a way to avoid these false positives?
Sonarqube squid:S2095 false positive
I found the answer. This is a known bug:https://jira.sonarsource.com/browse/SONARJAVA-1478ShareFolloweditedMar 24, 2016 at 10:00Tunaki135k4646 gold badges355355 silver badges431431 bronze badgesansweredMar 24, 2016 at 9:59Łukasz WoźniakŁukasz Woźniak37122 silver badges77 bronze badgesAdd a comment|
This question already has an answer here:When is an IntStream actually closed? Is SonarQube S2095 a false positive for IntStream?(1 answer)Closed6 years ago.I have a problem with SonarQube. The code belowStreamSupport.stream(var, false).mapToInt().collect(..);does not comply with the rulesquid: S2095 Resources should be closedWhat can I do to tell SonarQube to not scan features from Java 8 to that rule?
SonarQube and squidS2095 with Java 8 [duplicate]
Squid is a different kind of beast. As suggested in theSonarQube docs, you'll have to use a slightly different syntax, e.g.:@SuppressWarnings("squid:CallToDeprecatedMethod")The stringsquid:CallToDeprecatedMethodis the SonarQuberule key.Unfortunately, this means addingtwoannotations to effectively suppress the deprecation warning. But afaik, it's the only way short of disabling the rule.ShareFollowansweredOct 28, 2015 at 9:20barfuinbarfuin17.1k1111 gold badges8787 silver badges133133 bronze badges2why two, we can use both the annotations in the single annotation use?–KumarAnkitJan 14, 2019 at 9:54Sure, you can@SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"}), but that's syntactic sugar ;-) @KumarAnkit–barfuinJan 14, 2019 at 14:24Add a comment|
Is there any possibility to configure SonarQube 5.1 with Checkstyle plugin to honor the@SuppressWarnings("deprecation")annotation. I do not want to turn off 'Avoid use of deprecated methods' rule, I just want to SonarQube honor [email protected] have a Java code in which I need to use deprecatedcreateValidator()method as following:@SuppressWarnings("deprecation") @Override public javax.xml.bind.Validator createValidator() throws JAXBException { return contextDelegate.createValidator(); }Java compiler does not warning when compiling code, but unfortunately SonarQube with CheckStyle plugin rise a issue:squid:CallToDeprecatedMethod Avoid use of deprecated methods
Honoring @SuppressWarnings with the sonar checkstyle plugin
It is a known bug: please seehttp://jira.sonarsource.com/browse/SONARJAVA-583To provide more context here : This unused private method is relying on an old implementation and is (at time of writing my answer) being migrating to rely on semantic analysis and not only bytecode analysis.ShareFollowansweredSep 15, 2015 at 8:10benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badgesAdd a comment|
I have private method in my class.public class MyClass { public void method(){ .... List<String> filteredPaths = Arrays.asList(paths).stream().filter(this::validate).collect(Collectors.toList()); .... } private boolean validate(String path){ ... } }I see major issue:Private method 'validate' is never used.Is this issue known?How to fix it? workarounds?
SonarQube doesn't see method reference
Itisimpossible as long as you useCollections.toMap().You could copy-and-paste that function (and themapMerger()function on which it depends), declaring the return type asCollector<T, LinkedHashMap<K,U>, LinkedHashMap<K,U>>. But I think it would be better to keep your code clean and deal with Sonar. Perhaps there's a way to indicate that this is a false positive, and suppress warnings from Sonar.ShareFollowansweredJun 14, 2017 at 18:36ericksonerickson267k5858 gold badges397397 silver badges495495 bronze badges1That's what I thought, but I needed reassurance–NovaterataJun 14, 2017 at 19:08Add a comment|
I have a Collector function that is basically toMap but always a LinkedHashMap as I need this often. Sonar complains about the ? wildcard generic in the return type. Seeing as this is the exact same signature as the toMap method, and I'm at it's mercy, how would I replace the wildcard with a proper value or generic?I've triedMap<K,U>and adding anM extends Map<K,U>and LinkedHashMap versions of those as well, but nothing compiles.Any suggestions?Or is this impossible as I am using Collectors.toMap which uses a wildcard?public static <T, K, U> Collector<T, ?, LinkedHashMap<K, U>> toLinkedHashMap( Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> merger) { return Collectors.toMap(keyMapper, valueMapper, merger, LinkedHashMap::new); }Here is the full text of the Sonar rule:Generic wildcard types should not be used in return parametersCode smellMajorsquid:S1452Using a wildcard as a return type implicitly means that the return value should be considered read-only, but without any way to enforce this contract. Let's take the example of method returning aList<? extends Animal>. Is it possible on this list to add a Dog, a Cat, ... we simply don't know. The consumer of a method should not have to deal with such disruptive questions.Non-compliant Code ExampleList<? extends Animal> getAnimals(){...}
How to replace wildcard generic when customizing Collectors.toMap
I was able to do it this way:#pragma warning disable S100 public string DMSCode { get; set; } #pragma warning restore S100Not sure if this is the best solution, but it works here.ShareFollowansweredNov 10, 2016 at 17:37M Kenyon IIM Kenyon II4,17644 gold badges4747 silver badges9595 bronze badgesAdd a comment|
In our C# project we are using SonarQube/SonarLint.We have a property calledDMSCode.DMSis an abbreviation we use in our organization, so really is valid. Yet SonarLint is throwing an S100 warning.Is there a way to ignore this for this code:public string DMSCode { get; set; }I tried searching 'sonarlint s100 ignore' and some other variations, but found nothing.
Can we ignore a specific S100 warning with SonarLint
Managed to fix the issue using the below script in step 3:$Files= Get-ChildItem %system.teamcity.build.tempDir% ` -Filter coverage_dotcover*.data ` | where-object {$_.length -gt 50} ` | Select-Object -ExpandProperty FullName $snapshot =[string]::Join(";",$Files) & %teamcity.tool.dotCover%\dotCover.exe merge ` /Source=$snapshot ` /Output=%env.TEMP%\dotCoverReport.dcvr` & %teamcity.tool.dotCover%\dotCover.exe report ` /Source=%env.TEMP%\dotCoverReport.dcvr ` /Output=%sonar.coverageReport% ` /ReportType=HTMLShareFolloweditedMay 15, 2016 at 9:09harishr17.9k99 gold badges8181 silver badges127127 bronze badgesansweredDec 22, 2015 at 10:54developerdeveloper1,52144 gold badges2929 silver badges7777 bronze badges1Code coverage is working now. However, unit test results are still showing 0s.–developerDec 22, 2015 at 10:55Add a comment|
I am trying to upload Unit Test and dotCover Code Analysis results from TeamCity to Sonar server. It shows code coverage and unit test results in the TeamCity but no code coverage/unit test on Sonar.TeamCity Unit test step:Followed by Powershell script:I have the following additional parameter in Sonar Runner step:Dsonar.cs.vstest.reportsPaths=TestResults.trc Dsonar.cs.dotcover.reportsPaths='%sonar.coverageReport%'Does anyone know how to fix this?Thanks.
Team City Code Coverage and Unit Test results not showing on Sonar
You could define a variable for the break-condition and include it into the for-loop condition:boolean endLoop = false; for (Iterator<Integer> keys = integerKey.keySet(); keys.hasNext() && !endLoop; ) { Integer integer = keys.next(); if (map.containsKey(integerKey.get(integer))) { ... if (integerKey.get(integer).equals(min)) { endLoop = true; } } else if (integerKey.get(integer) <= min){ ... endLoop = true; } else { ... } }or declare a local variable in the loop which is set to true if the loop should left with a break:for (Integer integer: integerKey.keySet()) { boolean endLoop = false; if (map.containsKey(integerKey.get(integer))) { ... if (integerKey.get(integer).equals(min)) { endLoop = true; } } else if (integerKey.get(integer) <= min){ ... endLoop = true; } else { ... } if (endloop) break; }ShareFollowansweredSep 30, 2015 at 14:43werowero32.8k33 gold badges6060 silver badges8484 bronze badges1Oh yes I see, that is great. Thanks!–hacks4lifeSep 30, 2015 at 14:47Add a comment|
For code quality reason, I would like to refactor my code a little bit in order to use only onebreakstatement in my loop. But I am not sure I can do this the way SonarQube is aking me...Here's my code :for (Integer integer: integerKey.keySet()) { if (map.containsKey(integerKey.get(integer))) { TypeValue value = map.get(integerKey.get(integer)); sb.append(integerKey.get(integer)).append(":"); sb.append(encodeValue(value)); sb.append("|"); if (integerKey.get(integer).equals(min)) { break; } } else if (integerKey.get(integer) <= min){ TypeValue value = map.get(min); sb.append(min).append(":"); sb.append(encodeValue(value)); sb.append("|"); break; } else { sb.append(integerKey.get(integer)).append(":"); sb.append("0"); sb.append("|"); } }I would like to do the same thing but using only onebreakbut I am not sure I can write only oneifcondition in this case instead ofif-elseif-else.Any ideas ?Thanks.
How can I avoid using more than a single "break" statement in a loop?
This means that you have branches in your code that are not covered.For instance :boolean foo() { return a || b || c; }if in your tests you always have a that is true, then you are covering the line indeed but not all the branches possible.Please also watch out for try with resources as this generates a lot of branches in bytecode (and you don't see them in source) and you are most probably not covering all of them.ShareFollowansweredAug 19, 2015 at 11:32benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badgesAdd a comment|
Does anybody knows about this issue “Insufficient branch coverage by unit tests”? My class code coverage is 99% but I am keep getting sonar warning for that same class “Insufficient branch coverage by unit tests : 111 more branches need to be covered by unit tests to reach the minimum threshold of 65.0% branch coverage.” Normally this error occurred due to Insufficient coverage of if/else condition as we have to handle positive/negative both scenarios. Does anybody knows anything else about this warning?Thanks Sach
SonarQube warning "Insufficient branch coverage by unit tests"
Method with camera: we already know size for each device. You take a picture of device, calculate it's height/width to determine type of device (iPhone/iPod or iPad), than calculate a distance.For example - if device is iPhone you know, that its size is 115x58 mm. On picture it NxM pixels. Now you can calculate the distance. (If N & M smaller hence distance is larger)ShareFollowansweredMay 11, 2011 at 9:115hrp5hrp2,23011 gold badge1818 silver badges1818 bronze badges1GUess I'm going with Image Recognition algorithms now, looking into OpenCV while I type this.–BersaelorJun 22, 2012 at 20:33Add a comment|
Yeah, I'm currently wondering about this. In my use case the devices will be 50cm to 10m apart and I'd like it to be accurate to at least 10 cm. (Therefore GPS is not an option)2 Ways spring to mind:Sound: I asked about this in the dev forums and I'm in contact with laanlabs, about the code of theirsonar ruler.Picture on one device + Camera on the other: Seems easier to set up, since my user case involves the user facing one device at 90 degrees anyway. But it would be more work for the user to face the camero into the direction and it would not react to a change in distance.Now the question: Is anyone aware of any code that does something like this already? Possibly a non-iPhone general c-Project?
Measuring distance between two iOS Devices
In version 8.7 (the version we have), the redirect URL is controlled by the Server Base URL, keysonar.core.serverBaseURL. The description of the field mentions being used in the construction of emails, but it is also used as the callback.You can find it in the "General" tab of the settings.ShareFollowansweredMar 9, 2021 at 17:19Joe AtzbergerJoe Atzberger3,17911 gold badge1919 silver badges1717 bronze badges1Thanks a lot, it did work after configuring this attribute.–raedshariMay 3, 2023 at 12:54Add a comment|
I have a problem with authorization in Sonar Qube with Gitlab. The error is "The redirect URI included is not valid. ".My Sonar Qube is hosted on Azure VM Ubuntu. When I open the network in the browser I see that the redirect URL is "redirect_uri: http://localhost:9000/oauth2/callback/gitlab".Why in Gitlab Applications I put http://mysonarcubeIP/oauth2/callback/gitlab.Sonar Qube is community and Gitlab also.
Gitlab Sonar Qube Redirect Url
A dumb mistake from myside.Replacingsonar.javascript.lcov.reportPathswithsonar.typescript.lcov.reportPathssolved the issue.ShareFollowansweredSep 11, 2019 at 9:10Vasanth KumarVasanth Kumar32111 gold badge33 silver badges99 bronze badges21The docs say you can usesonar.javascript.lcov.reportPathsfor both js and ts.docs.sonarqube.org/latest/analysis/coverage–JBSAug 30, 2021 at 9:011As of this year (2023)sonar.typescript.lcov.reportPathshas been deprecated–CWSitesApr 25, 2023 at 14:53Add a comment|
I have written some unit tests in jest. All of them are successful. Able to view test coverage report generated by jestBut my sonarqube dashboard always shows 0% on coverage but unit tests are being detected.I am usingjest-sonar-reporterfor sonar consumable format generation of reports.This is my sonar properties filesonar.projectKey=skyflow-app sonar.projectName=Skyflow App sonar.host.url = http://localhost:9000 sonar.projectVersion=1.0 sonar.sourceEncoding=UTF-8 sonar.sources=src sonar.exclusions=**/node_modules/**,**/*.spec.ts, **/*.stories.tsx sonar.tests=src sonar.test.inclusions=**/*.test.tsx,**/*.test.ts sonar.test.exclusions=**/*.stories.tsx sonar.ts.tslintconfigpath=tslint.json sonar.testExecutionReportPaths=testResults/sonar-report.xml # sonar.coverageReportPaths = coverage/lcov.info sonar.javascript.lcov.reportPaths = coverage/lcov.infoPlease let me know where i am going wrong.
Sonarqube coverage 0% in react js
Well, it'll only happen for one item, so you couldmake it simpler and more obvious:var acordSubAccount = acordHolding.Investment.SubAccount.FirstOrDefault( sa => sa.ProductCode.Equals(productCode)); // possibly use == instead of .Equals? if (acordSubAccount != null) { acordSubAccount.OLifEExtension.Add(ACORDUtil.CreateOLifEExtension(OlifeExtensions)); return acordSubAccount; }ShareFollowansweredMay 10, 2019 at 15:20Marc GravellMarc Gravell1.0m271271 gold badges2.6k2.6k silver badges2.9k2.9k bronze badgesAdd a comment|
I'm using a code analysis software called SonarQube and it's giving me this error message saying that I should remove the return statement or make it conditionalI'm thinking about suppressing the message but not entirely sure yet.protected static SubAccount GetSubAccountByProductCode(Holding acordHolding, string productCode, string optionType) { var OptionTypeElement = ACORDUtil.CreateACORDElement("OptionType"); const string subAccountPrefix = "SubAccount"; var OlifeExtensions = new List<XmlElement>(); if (string.IsNullOrEmpty(optionType)) { OptionTypeElement.InnerText = "V"; } else { OptionTypeElement.InnerText = optionType; } OlifeExtensions.Add(OptionTypeElement); foreach (var acordSubAccount in acordHolding.Investment.SubAccount.Where(sa => sa.ProductCode.Equals(productCode))) { acordSubAccount.OLifEExtension.Add(ACORDUtil.CreateOLifEExtension(OlifeExtensions)); return acordSubAccount; } //sub account not found, create one for this product symbol. var newSubAccount = new SubAccount(); newSubAccount.id = string.Format("{0}-{1}", subAccountPrefix, productCode); newSubAccount.ProductCode = productCode; acordHolding.Investment.SubAccount.Add(newSubAccount); var oLifeExt = ACORDUtil.CreateOLifEExtension(OlifeExtensions); newSubAccount.OLifEExtension.Add(oLifeExt); return newSubAccount; }Make sonarqube not throw out an error message.
Remove this 'return' statement or make it conditional
SonarQube reads code coverage reports and marks which lines have been tested (covered by tests).not coveredmeans that those lines are not included in the code coverage reports. There are two options, your tests:don't check the code from the screencheck the code from the screen, but the code coverage report:didn't include data of these testshas not been generated and uploaded to the serverDocumentation aboutSonarQube Test Coverage & Execution.ShareFolloweditedAug 17, 2020 at 19:32answeredSep 13, 2018 at 19:08agabrysagabrys8,89833 gold badges3535 silver badges7575 bronze badges2you mentioned - those lines are not included in the code coverage reports. why SonarQube did that and when SonarQube will cover these lines?. I am also facing same issue. what needs to be done to resolve?–SSDAug 17, 2020 at 11:06SonarQube only displays coverage results produced by other tools. You have to use a coverage tool (like JaCoCo for Java), execute it and next performs SonarScanner analysis. If the lines are covered by tests, they will be marked as covered in SonarQube UI.–agabrysAug 17, 2020 at 19:31Add a comment|
I'm evaluating SonarQube Developer for our development team, and facing most of the lines are tagged as "Not covered by tests".I suppose "not covered" means "not checked or not tested". Am I guess right?Please let me know the exact meaning of "not covered" and why this happens.Below are the background info. of this evaluation.SonarQube 7.3 (BuildWrapper and SonarScanner for Windows)C/C++ Project using Qt 5.9Screenshot of SonarQube Console
SonarQube says "Not covered by tests" for most of lines
While you canexcludesome filesfrom coverage, you can onlyincludefiles as a whole. That is, exclusion is granular, but inclusion is not (i.e.sonar.coverage.inclusionsdoesn't exist), so I don't think this will work the way you're currently trying to do it.That said, this should be doable with only exclusions if you craft them carefully, i.e.**/model/*.javarather than**/model/**/*.java.ShareFollowansweredMay 21, 2018 at 16:07G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges3and what aboutClassToInclude? Should I exclude the rest of the package class by class?–Alvaro PedrazaMay 21, 2018 at 16:18... or reorganize your packaging.–G. Ann - SonarSource TeamMay 21, 2018 at 16:373That's not an option unfortunately, I'll take your answer. As a side note, it would be a great feature to addsonar.coverage.inclusionsproperty in a future version, do you have any feature request site?–Alvaro PedrazaMay 21, 2018 at 16:44Add a comment|
I'm trying to improve the coverage reports for my project and I want to exclude some packagesBUT INCLUDINGsubpackages. For instance, I have this structuresrc/main/java/com/myapp └ model └ mapper └ SomeMapperClass.java └ SomeModelClass.java --> exclude this and others... └ ... └ ClassToInclude.java --> but include this └ serviceand I want to excludemodelpackage but includemapperandClassToInclude. Is there any way to do this without having to add every excluded class one by one? I would want something like this inpom.xml:<sonar.coverage.exclusions> **/model/**/*.java </sonar.coverage.exclusions> <sonar.coverage.inclusions> **/model/mapper/**/*.java **/model/ClassToInclude.java <sonar.coverage.inclusions>Any help, guide, options and/or workarounds is appreciated. Thanks in advance for your answers.UPDATE #1I found a way to include the subpackages only usingsonar.coverage.exclusionsproperty by doing:<sonar.coverage.exclusions> **/model/*.java </sonar.coverage.exclusions>With this you exclude every class inmodelbut not inmodel.mapper. Now I just need a way to solve how to include specific class in an excluded package.
Sonar exclusions/inclusions
To create additional groups(similar to "sonar-administrators") with admin permissions.Create a new Group with the same name as displayed in your AD.Restart the sonar to pick up the changes.Grant the new group admin permissions using the sonar API.curl -X POST -v -u admin:Password 'http://mysonar/api/permissions/add_group?permission=admin&groupName=mynewgroup'ShareFollowansweredJan 26, 2017 at 6:03bharat samabharat sama5633 bronze badgesAdd a comment|
I create a SonarQube groupsonar-administrators-ldapand mapped to LDAPsonar-administrators-ldap. Users undersonar-administrators-ldapare able to login successfully.When navigate tohttp://localhost:9000/roles/global, it only shows two default groups:Anyoneandsonar-administrators, but not the newsonar-administrators-ldapgroup.How do I grant/revoke global permissions for groups other the default groups?
Grant group global permissions similar to sonar-administrators
I use docker-compose and this option works perfectly for me.version: "2" services: sonarqube: image: sonarqube command: -Dsonar.ce.javaOpts=-Xmx4096mYou can costumize the memory size.ShareFollowansweredApr 9, 2019 at 6:43Arief KarfiantoArief Karfianto24533 silver badges88 bronze badgesAdd a comment|
I am gettingOutOfMemoryExceptionwhile performing sonar analysis on my project. Jenkins job shows analysis report was generated successfully but during background task inSonarQubeit is failing with below exception.,2016.08.24 10:55:52 INFO [o.s.s.c.s.ComputationStepExecutor] Compute comment measures | time=14ms 2016.08.24 10:56:01 INFO [o.s.s.c.s.ComputationStepExecutor] Copy custom measures | time=9075ms 2016.08.24 10:56:02 INFO [o.s.s.c.s.ComputationStepExecutor] Compute duplication measures | time=150ms 2016.08.24 10:56:34 ERROR [o.s.s.c.c.ComputeEngineContainerImpl] Cleanup of container failed java.lang.OutOfMemoryError: GC overhead limit exceeded 2016.08.24 10:56:34 ERROR [o.s.s.c.t.CeWorkerCallableImpl] Failed to execute task AVa6eX7gdswG1hqK_Vvc java.lang.OutOfMemoryError: Java heap space 2016.08.24 10:56:34 ERROR [o.s.s.c.t.CeWorkerCallableImpl] Executed task | project=iServe | id=AVa6eX7gdswG1hqK_Vvc | time=53577ms
SonarQube java.lang.OutOfMemoryError: GC overhead limit exceeded
FxCop integration: extend theTemplate for custom FxCop rulesin SonarQube (fxcop:CustomRuleTemplate) by specifying theCheckIdof your custom FxCop rule. [edit] FxCop rules are now covered by thesonar-fxcopplugin.StyleCop integration:deprecatedas StyleCop doesn't rely on Roslyn.ShareFolloweditedMar 14, 2017 at 8:29answeredMay 9, 2016 at 11:44Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badges1There in in internet a good example? Probably I don't fill the fields correctly. I have to provide a separate xml file to include the FxCop rule in SonarQube, or I have to modify or add something in the project of the rule?–grandeale83May 10, 2016 at 10:40Add a comment|
I'm using SonarQube 5.4 to analyse my own C# code, the analysis works as I expected. Now I have written some custom rules, one using StyleCop and another using FxCop to run on my code, but I don't find how to import theese custom rule in SonarQube. I underline that I use SonarQube 5.4 with C# plugin 5.1. In my installations the folder "rules" doesn't exists. Instead I can find:sonar-fxcop-library-1.3.jar in /opt/sonarqube-5.4/data/web/deploy/plugins/csharp/META-INF/lib and sonar-stylecop-plugin-1.1 in /opt/sonarqube-5.4/extensions/plugins.Anyone can help me to import my custom rules in SonarQube installation?
Sonarqube 5.4 custom rule for C#
I understand the arguments for maintaining the stack trace and all that, but I think it's going to bloat your logs for a < ERROR level event. One solution is to log the message as a WARN and log the exception object as DEBUG or TRACE. That way a normal user log config would not be flooded with business as usual stack traces, but it would still be possible to get a stack trace if necessary.ShareFollowansweredMar 8, 2017 at 13:33NovaterataNovaterata4,52333 gold badges3131 silver badges5454 bronze badgesAdd a comment|
Quote from the description of the rule (SonarQube 4.5.5):// Noncompliant - exception is lost (only message is preserved) try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); }By providing the exception class to the logger a stack trace is written to the logs.The problem in our code base is this: By following theTell, don't askprinciple, we use checked exceptions as part of the, what we consider, normal execution paths and we don't want them to result in unreasonably large log messages.A few examples: Servers responding with error codes, database statement executions failing on optimistic locking (concurrent users)...My suggestion: Split this case in two.// Noncompliant - exception is lost (only message is preserved) try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); }and// Compliant - exception is lost (only message is preserved) but there is business logic handling the situation try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); */ exception handling */ }The rulesquid:S00108(code blocks must not be empty) would not catch the problem since there is a logging statement.Is this not reasonable? Have I missed something of importance?Note: I've rewritten the question to clarify my use case
Why does squid:S1166 not accept exception messages only when logging caught exceptions?
Have a look athttp://docs.sonarqube.org/display/DEV/Extend+Web+Application. See section Applications -> Development mode.RegardsShareFollowansweredJun 11, 2015 at 13:08Julien L. - SonarSource TeamJulien L. - SonarSource Team2,5771717 silver badges1515 bronze badges4There is a useful information there, but it does not say anything about debugging code using IDE (i.e. stopping on breakpoints etc...)–SergeyJun 11, 2015 at 14:18I'm not aware of being able to set some break point in rails code. On my side, I'm using some good old : puts "### Blabla" to understand what happen...–Julien L. - SonarSource TeamJun 12, 2015 at 7:27There is such option. See for examplejetbrains.com/ruby/features/ruby_debugger.htmlUsing "puts" works too, but productivity will be completely different.–SergeyJun 14, 2015 at 7:17You can putbinding.pryat arbitrary point in code to pause execution and drop into pry console. This will work in the context of a Rails server as well. This is not an IDE way though and will require some setup. SeePry Runtime invocationfor more.–Nic NilovJun 16, 2015 at 12:07Add a comment|
What is the way to debug Rails and Ruby code (i.e. breakpoints, call stack etc...) which is running inside a separate JVM using IDE (IntelliJ Idea)? What configuration is required for it in Sonarqube and IntelliJ?I did not find this information on Sonarqube site or elsewhere.
Debugging Ruby and Rails code inside Sonar plugin
InSonarRunnerBuilderclass there is aprojectattribute that represents the path to a file with properties for the project.In the same way in which you set the JDK (jdk('(Inherit From Job)')) you can set the path property. In your example, try like this:StepContext.metaClass.sonar = { -> NodeBuilder nodeBuilder = new NodeBuilder() stepNodes << nodeBuilder.'hudson.plugins.sonar.SonarRunnerBuilder' { jdk('(Inherit From Job)') usePrivateRepository(false) project('${your.path.here}') } }ShareFolloweditedMay 1, 2021 at 1:43answeredApr 27, 2015 at 16:15Bruno RibeiroBruno Ribeiro6,01755 gold badges4141 silver badges4949 bronze badges1I was looking for something like that. Thanks.–FrancoisApr 28, 2015 at 7:19Add a comment|
Using Job-DSL we can configure a C# project in Jenkins.The SonarQube tasks is giving us a hard time.StepContext.metaClass.sonar = { -> NodeBuilder nodeBuilder = new NodeBuilder() stepNodes << nodeBuilder.'hudson.plugins.sonar.SonarRunnerBuilder' { jdk('(Inherit From Job)') usePrivateRepository(false) } }How to set the path to thesonar-project.propertiesconfig file, using the Job-DSL script?Final scriptThanks to @Bruno César, I addedpathToSonarProjectPropertiesas parameter.StepContext.metaClass.sonar = { String pathToSonarProjectProperties -> NodeBuilder nodeBuilder = new NodeBuilder() stepNodes << nodeBuilder.'hudson.plugins.sonar.SonarRunnerBuilder' { jdk('(Inherit From Job)') usePrivateRepository(false) project(pathToSonarProjectProperties) } }Thesonarfunction is called with the relative-to-project-root path ofsonar-project.properties:sonar("Framework\\xxx\\xxx\\sonar-project.properties")
Configure Jenkin's SonarQube section using Job-DSL
I have finally found the problem seeking for a different one (Tomcat WST server started but Eclipse was unable to connect to it and timed out).The problem comes from a strange and unpredictable behavior of the SOCKS proxy parameter.When SOCKS proxy is defined, in some undefined cases, both starting a WST server or connecting to a SonarQube server through the plugin fail, whereas other functions like plugin installs work like a charm.The solution came fromhttps://stackoverflow.com/a/6459816/256561and is to clear SOCKS proxy settings.ShareFolloweditedMay 23, 2017 at 12:14CommunityBot111 silver badgeansweredSep 27, 2013 at 13:53Doc DavluzDoc Davluz4,19055 gold badges3131 silver badges3333 bronze badgesAdd a comment|
I have installed the latest version on the Sonar Eclipse Plugin on an Eclipse Juno 3.8. I am desperatly trying to connect the plugin to our running instance of Sonar. I'm behind a NTLM v2 Proxy. Hereunder, details of my configuration and my attempts.Versions of products :Eclipse 3.8,Sonar Eclipse Plugin (Java Analyzer & m2e Connector) 3.2.0.20130627-1142-RELEASE,SonarQube Server 3.7 (running onhttp://source01:9000, in the LAN, not behind the proxy, direct connection possible).Trying to access with the following proxy configurations with an without http_proxy variable in the configuration:direct with http_proxy : failure,direct without http_proxy : success (but unable to use other Eclipse feature accessing Internet like the Marketplace),native (with or without http_proxy) : failure,manual (with or without http_proxy): failure.I systematically got org.apache.http.conn.ConnectTimeoutException in the logs (trying to accesshttp://source01:9000/api/authentication/validatewhich work in a browser).No more idea on what to test.
Unable to connect Sonar Eclipse Plugin to Sonar Server
Pylint rely on properPYTHONPATHbeing set. What happens if you typepython toplevel/directoryA/file.py? Imports should work then.Hint: if they don't, you probably want to runexport PYTHONPATH=toplevel, or something like that.ShareFolloweditedNov 29, 2017 at 13:15Ian Mackinnon13.7k1313 gold badges5555 silver badges6767 bronze badgesansweredJul 24, 2013 at 15:36sthenaultsthenault14.7k55 gold badges3838 silver badges3232 bronze badges1I am not sure how to set PYTHONPATH. I am newbie and trying to learn. I have tried exporting PYTHONPATH the way you said but it didnt worked. Is tere any thing related to VIRTALENV? I am using VIRTENV.–hjelpmigJul 29, 2013 at 8:48Add a comment|
I am playing around with pylint and using sonarqube for code analysis. Everything is installed and working fine. However I am getting error "f0401" saying that I am unable to import module. Here is my directory structure.top level: directoryA __init__.py folderA some .py files directoryB __init__.py folderA some .py files directoryC __init__.py folderA some .py filesI am running pylint on directoryA. the .py files in directoryA have some imports from the directoryB and directoryC. So when I run pylint on directoryA i get import errors such as unable to 'import directoryB.somemodule'. I hope that I am able to explain it clearly.Can some body help he how to solve that problem. P.S. It will be great if some ´body point me out to some good documentation and tutorials for using and tweaking pylint.
unable to import module error in pylint
Why not install theSonar Eclipseplugin?This was designed to solve the following problems:Sonar does not support parallel analysis of the same project. This issue rules out the option of each developer running Sonar locally. (SeeSONAR-2761,SONAR-3306)You don't really want developers uploading metrics and source code into the Sonar database. They could be working on an uncommitted workspace and would therefore cause both inaccuracies and confusion if Sonar is being used for code review.Sonar is really designed to be run from a continuous integration server (like Jenkins), building code that has been submitted onto a shared codestream (or branch)The big advantages of using the Eclipse plugin are:True local analysis, no updates of the Sonar databaseConfiguration of the other tools is retrieved from the Sonar server and jars automatically downloaded.Centralized management of Sonar quality profilesShareFollowansweredFeb 7, 2013 at 21:03Mark O'ConnorMark O'Connor76.6k1010 gold badges140140 silver badges186186 bronze badgesAdd a comment|
We are trying to install a CI Platform with (Jenkins,sonar,eclipse ...). So that every developer can make analysis on his code before commit, I'm wondering between two alternatives :running local analysis with the sonar plugin.install the different plugins that sonar use (findbug,pmd,checkstyle ...) and configure them to meet the sonar configuration.I'm not sure which alternative to use? I used to work with findbugs,pmd, checkstyle in eclipse and they look great. Can you tell me which is the best alternative? Thanks in advance.Regards.
Eclipse sonar plugin vs findbugs+pmd+checkstyle eclipe plugins
There is no cast in your source code, but in the bytecode resulting from compilation there is. In the bytecode, the generic types are erased. The erasure forPis its first bound,ComponentContainer. So the bytecode is (almost) equivalent to the bytecode of this:public static void addComponentAligned(ComponentContainer parent, Component child, Alignment alignment) { parent.addComponent(child); ((AlignmentHandler)parent).setComponentAlignment(child, alignment); }Findbugs looks at that bytecode, and concludes that that cast to AlignmentHandler might fail, because (as far as findbugs sees) the method accepts any ComponentContainer.This is a findbugs bug; you should open a bug report. It looks to me like something that can be fixed without needing to analyze the source code. The bytecode also contains the real (generic) types, and findbugs should use that.ShareFollowansweredJul 5, 2012 at 11:10Wouter CoekaertsWouter Coekaerts9,55533 gold badges3131 silver badges3535 bronze badges0Add a comment|
The following code raises a "Unchecked / unconfirmed cast" critical violation using Sonar + FindBugs:1 public static <P extends ComponentContainer & AlignmentHandler> void addComponentAligned(P parent, Component child, Alignment alignment) { 2 parent.addComponent(child); 3 parent.setComponentAlignment(child, alignment); 4 }Any ideas of how should I avoid this violation?EDIT: Violation is on line 3EDIT: Method signatures follow: ComponentContainer#addComponent(Component) AlignmentHandler#setComponentAlignment(Component, Alignment)
Unchecked / unconfirmed cast using generics multiple bounds
The message is quite clear: the package declaration is wrong. It should be API.com.API if the source directory is /junk/test/src/main/java (that is the default value in Maven). An alternative is to change the source dir to src/main/java/API.ShareFollowansweredSep 10, 2011 at 12:37Simon BrandhofSimon Brandhof5,13611 gold badge2222 silver badges2828 bronze badges2if the package declration is wron my mvn clean compile install also failed it throws the exception while issuing mvn sonar:sonar log file can be found at [link]sonar-dev.787459.n3.nabble.com/file/n3325121/log-files–anishSep 10, 2011 at 14:41Any Update on this , i'm blocked on this or my Q is not clear–anishMay 28, 2012 at 15:55Add a comment|
Please note :- My mvn clean install goes successfulbut when i do mvn sonar:sonar it throws me[ERROR] Squid Error occurs when analysing :/junk/test/src/main/java/API/com/API/HelloAPI.java org.sonar.squid.api.AnalysisException: The source directory does not correspond to the package declaration com.API at org.sonar.java.ast.visitor.PackageVisitor.checkPhysicalDirectory(PackageVisitor.java:93) [sonar-squid-java-plugin-2.8.jar:na] at org.sonar.java.ast.visitor.PackageVisitor.createSourcePackage(PackageVisitor.java:75) [sonar-squid-java-plugin-2.8.jar:na]http://sonar-dev.787459.n3.nabble.com/file/n3324837/squid-test.zip
mvn sonar:sonar throws exception while doing Java AST scan
The method we are using is this:we built a custom pom.xml build file specific for sonar (we are using ant for other build purposes)it only has to perform test well, so specified hardcoded dependency references with<scope>system</scope>we didn't change the project structure for maven, you can specify in maven custom scr, test, resources directories (as long as you have only one src and test directory)the command used in CI ismvn clean compile sonar:sonarWe are using Continuum for the CI part, but it should work just as well in Hudson.This method did not change any other build items, it's just custom made for Sonar. But it does open the way for a Continuous Integration (daily) build, or for using maven as a build tool. This method is similar to the "sonar light mode" describedhereMore information here:http://docs.sonarqube.org/display/SONAR/Documentationhttp://docs.codehaus.org/display/SONAR/Continuous+IntegrationShareFolloweditedMar 4, 2015 at 16:11schnatterer7,64977 gold badges6363 silver badges8181 bronze badgesansweredAug 4, 2009 at 15:00Mercer TraiesteMercer Traieste4,67033 gold badges2424 silver badges2424 bronze badgesAdd a comment|
Hi Ladies and Gentlemen,We've quite big project with own build framework, based mostly on Java (however other languages exist).We'd like to use Sonar Hudson plugin to graphically present various code metrics. How do we do this?Do we need to change project structure and bring it to maven or there is a workaround to just specify where to get test results and other artifacts from?Thank you
Sonar project integration
It's possible to set that parameter using configuration application settings, no need to create a new container.In the portal go to application settings and add a new application setting. The name will be SONAR_ES_BOOTSTRAP_CHECKS_DISABLE and the value will be true. This passes the variable to the container and allows it start.ShareFollowansweredDec 9, 2022 at 23:45jvilaltajvilalta6,74911 gold badge2828 silver badges3636 bronze badges1Thanks for the reply. I set it this way, but forgot to answer.–Lionel DApr 3, 2023 at 6:37Add a comment|
I try to install sonarqube container on an Azure WebApp.It works fine as long as you use the H2 database. Unfortunately, this database is emptied each time the container restarts. Therefore, i'm trying to use SQLServer instead of H2.Everything works fine when the container is hosted on my machine. But on the WebApp, i get an issue form the underlying ElasticSearch:max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]I'm not a Linux power user, but as far as i could read, it can only be changed on the host machine which i cannot tweak. I've tried to use different containers such as this one:https://azure.microsoft.com/en-in/resources/templates/101-webapp-linux-sonarqube-azuresql/I've alsofollowed this tutorial:https://www.natmarchand.fr/sonarqube-azure-webapp-containers/Nothing works :(Has anyone succeeded to install a Sonarqube container on Azure with SQL Server as database? Or has anyone solved the issue mentioned above? Thanks a lot for your feedbacks.
Sonarqube container on Azure WebApp and SQLAzure
IMO it's because that could get confusing. Consider below, read the comment:class Child extends Super{ public void myMethod() { System.out.println("in child"); } } class Super{ public static void main(String[] args) { Super s = new Child(); s.myMethod(); // At this point you might expect myMethod of child to be called if it'll call the Parent's since it is private. } private void myMethod() { System.out.println("in super"); } }ShareFollowansweredJan 11, 2019 at 16:57Aditya Narayan DixitAditya Narayan Dixit2,1351313 silver badges2424 bronze badges11The question asks when the two methods are private. In your example, if the two methods are private, you should not wonder whether the Child method may be invoked, you know that onlySuper.myMethod()may be invoked in the current context.–davidxxxJan 12, 2019 at 9:48Add a comment|
Sonar complaining about private method name in a class when we using the same name of parent private method. In code quality what is the disadvantage of defining a private method with the same name of parent private method?Or do we need to categorize this as false positive
Sonar Rename this method; there is a "private" method in the parent class with the same name
Instead of loading the rules (you'd have to write a plugin for that) consider just loading the issues. TheGeneric Issue Datafeature was added recently (7.2) for just that case.Edit:Currentdocs hereShareFolloweditedSep 20, 2023 at 14:55answeredJul 24, 2018 at 13:08G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges2The link is now broken :(–ZymotikSep 20, 2023 at 10:011Thanks for the ping @Zymotik. New link added–G. Ann - SonarSource TeamSep 20, 2023 at 14:55Add a comment|
I have found this xml with style rules:https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml.I would like to save developers time from manually flagging non-conformities by loading the list into SonarQube but I haven't been able to figure out how.Anyone able to help me?
How can I automatically load the Google Style Rules to SonarQube?
It's not a bug but rather inherent limitation of the method SonarQube uses to check the code (static code analysis): SonarQube cannot generally evaluate the expressions (imagine if the condition depended on user input), so it cannot know whether the "else" branch will be executed or not.All it sees is that you initializetotalto0.0, and that you latermightcall code that tries to divide bytotalwhile it's still zero (it knows you didn't assign anything else into it, or found a branch where it remains zero).ShareFollowansweredJun 22, 2018 at 6:34Jiri TousekJiri Tousek12.3k55 gold badges3131 silver badges4545 bronze badges4Thanks. So actually there is no risk in my codes, right?–wu junlongJun 22, 2018 at 6:46@wujunlong No, there is no risk, but you can get rid of the warning with(total < 10E-6 || total == 0) ? 0 : (1.0 / total)–GlainsJun 22, 2018 at 7:04How can I make this warning on sonarQube disappear if it is not a bug?–CeciliaNov 6, 2019 at 21:08@Cecilia see Glains' comment.–Jiri TousekNov 7, 2019 at 8:15Add a comment|
for below codesdouble total = 0.0; //do something for total, anyway return total < 10E-6 ? 0 : (1.0 / total);Then sonar indicates me "Make sure "total" can't be zero before doing this division.". But if total is zero, it even won't reach 1.0/total. Is this a sonar bug, or my fault?
Why I violate SonarQube java rule "Zero should not be a possible denominator"
Well, it's not possible to do such a thing yet, as Fabrice said.I have a similar preview problem at work, so I just put up alocal instanceof a SonarQube Server in my computer, with all the rules/quality profiles/quality gates as my company.That way, i can run as manysonar:sonaras i need, testing it locally before the commit, just by specifying the "Dsonar.host.url" parameter.I don't know if that would solve your problem, but is definitely a way out.ShareFollowansweredJul 12, 2017 at 14:27Rafael CostaRafael Costa17399 bronze badgesAdd a comment|
We have our project integrated with SonarQube remote server, with aQuality Gateconfigured. Everytime we commit in master our gitlab executes that sonar:sonar and if the code doesnt meet the Quality Gate metrics , the build is rejected.I would like to do the same in local before pushing to Gitlab.If I executesonar:sonarin local pointing to the remote SonarQube server it verifies the Quality Gate and persists the metrics in the server.But, I would like to do the same without persisting the metrics as it's my own branch. So, if I use-Dsonar.analysis.mode=previewit doesnt persist metricsbut it doesnt check the metrics ( Quality Gate )Is there any way to do it ?
How can I use Sonar maven plugin to validate local code against Quality Gate?
If you use SonarQube up to version 5.6: Use theSonar Timeline Plugin, which allows you to add a graph to your dashboard.If you use SonarQube version 6.5 or later (to be released in August 2017): Getfeature rich history graphsout of the box (no plugin required)!ShareFollowansweredJul 11, 2017 at 7:34slartidanslartidan20.9k1616 gold badges8888 silver badges135135 bronze badgesAdd a comment|
I am triggering a Sonar analysis from Jenkins whenever a user commits any change to any branch of my project. In SonarQube I see the project analysis result, and quality gate status, for the most recently run analysis. It only shows the most recently run analysis for a given project.How can I see a 'history' of previous analyses that were run prior? Specifically I would like to see the coverage from before and the where in the codebase specific 'critical' issues triggered a quality gate failure. Basically I want a historical snapshot of the 'project overview' page for each time the analysis is run. Since I am triggering the analysis from different branches I need to be able to differentiate an analysis of Branch A vs. a previous analysis of Branch B.
See history of Sonar analyses in SonarQube
This is a known invalid issue:#14(he problem occurs on the server side, not inBuild Breakermechanism/logic).Matthew DeTullio's comment:This is because the server side background task for your project is failing. You need to check the logs there and fix that problem first. The report processing step is when SQ computes the quality gate status. This plugin simply checks the status computed there, so if processing fails this plugin will mark the analysis a failure.In my company we found on the server side:java.lang.OutOfMemoryError: GC overhead limit exceededShareFolloweditedOct 2, 2017 at 12:45answeredOct 2, 2017 at 12:01agabrysagabrys8,89833 gold badges3535 silver badges7575 bronze badges3I am getting a similar error. Does not seem to be an issue with Java OOM.–UpenSep 20, 2018 at 4:371Please create a new question and add logs. Maybe I can help you, but comments are not a good place for that.–agabrysSep 20, 2018 at 7:242For me the issue was due to multi module maven project. Individual modules under the multi module project had reports available on Sonar. So when the multi module project was trying to publish the reports had a conflict. I removed all the individual module reports and it went fine.–UpenDec 4, 2018 at 22:26Add a comment|
I am trying to upload reports generated by Istanbul to Sonar dashboard using a gulp task and it fails with the below error. Looks like theBuild Breakerplugin in SonarQube is timing out before it can upload the report to Sonar. Any way that i can tweak this plugin?I am using Sonar 5.3.15:42:43.411 INFO: Analysis report generated in /workspace/{project}/.sonar/report 15:42:43.430 INFO: ------------------------------------------------------------------------ 15:42:43.430 INFO: EXECUTION FAILURE 15:42:43.430 INFO: ------------------------------------------------------------------------ 15:42:43.430 INFO: Total time: 5:06.287s 15:42:43.609 INFO: Final Memory: 57M/2603M 15:42:43.609 INFO: ------------------------------------------------------------------------ 15:42:43.609 ERROR: Error during SonarQube Scanner execution java.lang.IllegalStateException: Report processing did not complete successfully: FAILED at org.sonar.plugins.buildbreaker.QualityGateBreaker.getAnalysisId(QualityGateBreaker.java:152) at org.sonar.plugins.buildbreaker.QualityGateBreaker.execute(QualityGateBreaker.java:108) at org.sonar.plugins.buildbreaker.QualityGateBreaker.executeOn(QualityGateBreaker.java:95) at org.sonar.batch.phases.PostJobsExecutor.execute(PostJobsExecutor.java:65) at org.sonar.batch.phases.PostJobsExecutor.execute(PostJobsExecutor.java:55)
SonarQube Build Breaker plugin: Report processing did not complete successfully: FAILED
Generally the answer would be the space in your command. So, not-D project.settings=...but-Dproject.settings=...But that property was dropped. You'll just need to shuffle the properties files in/out of the "correct" name.ShareFolloweditedNov 9, 2016 at 14:23answeredNov 8, 2016 at 20:45G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges4Yeah, I thought so too, but with or without the space, the result is the same in all scenarios..–worldpartNov 8, 2016 at 21:21I double-checked everything - spelling, arguments, spaces, tried using quotes and relative/absolute paths.. I also know that the cmd argument works, because if I remove sonar-project.properties file, only leave sonar-project-local.properties file and run the analysis with the argument, scanner picks it up. If I run it without the argument - it doesn't.–worldpartNov 8, 2016 at 21:28@worldpart that is indeed another question. Please post it separately. :)–G. Ann - SonarSource TeamNov 10, 2016 at 16:45Done!–worldpartNov 10, 2016 at 16:56Add a comment|
I'm trying to run the analysis locally using Sonar-Scanner 2.6 pointing to SonarQube 5.4. The local solution folder contains thesonar-project.propertiesfile used in the cloud analysis.I am trying to create the properties file to be used locally, that is separate from the globalsonar-project.propertiesfile. This is the command that I ran:sonar-scanner -D project.settings=sonar-project-local.propertiesExpected behavior: Of the two files (sonar-project.propertiesandsonar-project-local.properties), sonar-scanner would choose the local one.Observed behavior: If the filesonar-project.propertiesexists, sonar-scanner uses the global one and ignores the local one.If I remove (rename) the global file from the directory, then the local file is recognized, and behavior is as expected.Is this a bug? What is the way to solve this issue without messing with the global properties file?
SonarQube Local Analysis - specify properties file
Make sure you are giving path in Global Tool Configuration correctly. Give the path of folder in which bin folder is exists inside that folder.Step1: 1st find where the sonar_scanner bin is available -root@test1sp117:/opt/sonar_scanner/sonar-scanner-3.0.3.778-linux# ls bin conf jre libStep2: Give the correct path in Manage Jenkins --> Global Tool Configuration --> SonarQube ScannerShareFollowansweredSep 15, 2017 at 9:22Harsha BiyaniHarsha Biyani7,1621010 gold badges3838 silver badges6262 bronze badgesAdd a comment|
I am trying to run the SonarQube Scanner within Jenkins as a post-build step. However, I keep getting the error message below:------------------------------------------------------------------------ SONAR ANALYSIS FAILED ------------------------------------------------------------------------ FATAL: SonarQube Scanner executable was not found for SonarQube Build step 'Execute SonarQube Scanner' marked build as failureFromsimilar questionson stackoverflow I read that one should choose "Install automatically" for the SonarQube Scanner, which I have done.My configurations is as follows:SonarQube 6.0Jenkins 1.609.3SonarQube Plugin 2.4.4SonarQube ServersSonarQube ScannerBuild-step
SonarQube Plugin for Jenkins does not find SonarQube Scanner executable
It seems that the feature I'm looking for will be in the release 5.2:https://jira.sonarsource.com/browse/SONAR-6106ShareFollowansweredOct 14, 2015 at 11:37Andreas ScharfAndreas Scharf13611 gold badge22 silver badges1010 bronze badges1Besides the mail notification, I want also to be notified via IRC channel. Best would be if the notification goes directly to the IRC user who caused it (so the user has to specify the IRC nickname somewhere). Is there maybe a plugin for SonarQube with these features?–mihcaJan 29, 2020 at 9:29Add a comment|
We want every user to get an email about new issues they introduced in this analysis.I found this request here, saying it should already have been possible:http://jira.sonarsource.com/browse/SONAR-2747Is it a matter of configuring SonarQube or did they remove the feature in the meanwhile? Unfortunately this is not documented anywhere and the Jira request does not say anything about the solution itself.[EDIT]What I want is following scenario:A commits a new issue.B commits a new issue. SonarQube analysis is run. (nobody actively changed something; e.g. reassigned issues)A gets a mail saying that he introduced1 new issue.B gets a mail saying that she introduced1 new issue.A and B can (if they subscribed) get another mail saying that there aretwo new issuesin total.[/EDIT]
How to enable notifications for the assignee of new issues in SonarQube?
This feature is not planned for the moment - even though it has already been discussed a couple of times.Multiple inheritance offers some good features that we can understand. Your use case is a good example. But it also brings complexity when it comes to decide what to do when you inherit the same rule from 2 quality profiles and this rule is activated differently on those 2 profiles.ShareFollowansweredJun 18, 2015 at 14:18Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges3One, in my mind, reasonable approach to the "deadly Diamond of Death" problem would be not to allow it. That the Quality Profile with multiple rule inheritance is considered broken until it's made unambiguous.–AlixJun 22, 2015 at 8:171Indeed, but then this means adding lots of validation when you update any quality profile => what happens when you update profile A and this makes profile Z ambiguous because it somehow inherits from A?–Fabrice - SonarSource TeamJun 22, 2015 at 9:09Yeah, I guess it would be good to detect any such errors early. A less strict approach would be to skip any ambiguous rules during analysis (with a warning/error message)–AlixJun 23, 2015 at 7:56Add a comment|
I see a need for multiple inheritance for Quality Profiles to avoid unnecessary manual work when we upgrade.For example we would like to inherit all rules from "Sonar Way" and from "Android Lint" and restore the built-in profiles after each upgrade, making sure we are always up to date.Is this feature planned for?
Multiple inheritance for Quality Profiles
This means that you haveprovisioned your projectto be able to make a local analysis in Eclipse.Local analyses(like what happens in Eclipse) don't push data to the server - they are used to "preview" the quality of your codeRegular analysesdo push the results to the server. You run such an analysis with Maven, SonarQube Runner, Ant, Gradle, Jenkins, ...So if you want to see the results inside SonarQube Web application, just a regular analysis. Everything is explained in"Analyzing Source Code" documentation section.ShareFollowansweredJan 22, 2015 at 16:26Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges2Is there any way for eclipse to push the results to the server?–Dinesh PanchananamJan 23, 2015 at 6:45No, this is forbidden.–Fabrice - SonarSource TeamJan 23, 2015 at 12:09Add a comment|
I'm a SonarQube newbie. I'm running analysis in eclipse via sonar-eclipse-plugin. But on remote server, it displays:No analysis has been performed since creation. The only available section is the configurationHow can I see the results of the analysis on the server?
SonarQube: No analysis has been performed since creation. The only available section is the configuration
As I explained onWhich sonar-maven-plugin version to use?, the plugin you have to use isorg.codehaus.mojo:sonar-maven-plugin, not the internal one(s). (So no need to try to upgrade sonar-maven3-plugin)Your issue probably comes from the fact that the version oforg.codehaus.mojo:sonar-maven-pluginhas been locked down in your POM or parent POM.ShareFolloweditedMay 23, 2017 at 12:16CommunityBot111 silver badgeansweredJan 21, 2015 at 12:32Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges1Good to know. I was using org.codehaus.sonar ones. Thanks for your help.–Richard ForeseeJan 22, 2015 at 15:44Add a comment|
I have tried to upgrade sonar-maven3-plugin to 5.0, when executing an analysis on the new 5.0 server. I received the following error:[ERROR] Failed to execute goal org.codehaus.sonar:sonar-maven-plugin:5.0:sonar (default-cli) on project demo-issues: Please update sonar-maven-plugin to at least version 2.3 -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.sonar:sonar-maven-plugin:5.0:sonar (default-cli) on project demo-issues: Please update sonar-maven-plugin to at least version 2.3 .Looking at the release notes, it says: "[SONAR-5705] - Drop support of Maven 2". Not only drop, the Mojo directly throws an exception. The problem is that the old maven 3 plugin (the 5.0 version) still points to the maven2 one.Is there any way to run an analysis with the 5.0 maven plugin?
Sonarqube 5.0 maven plugin support (deprecated maven 2)
Yoursonar.sourcesproperty should point to the root ofAndroidManifest.xmlfile. E.g. if yourAndroidManifest.xmlfile is located insrc/mainthen yourbuild.gradlefile should contain:sonarRunner { sonarProperties { ... property "sonar.sources", "src/main" property "sonar.profile", "Android Lint" ... } }If you need more paths insonar.sourcesyou can put them as a comma-separated list.You can find how Sonar Android Plugin determines whether to run the analysis in itssource code.ShareFollowansweredJul 6, 2014 at 18:35Artur StepniewskiArtur Stepniewski1,44122 gold badges1111 silver badges1010 bronze badgesAdd a comment|
I have got the following trouble: I have installed SonarQube and Android Plugin with "Android Lint" Quality Profile. When I execute mybuild.gradlescript with "Android Lint" profile, sonar-runner plugin works good, but in SonarQube I can see no matching issues found, just zero.Nevertheless, when I include another profile –not "Android Lint"– I can see a lot of issues. Also in my android SDK when apply it's own lint I can see 157 issues. What it can be?sonar - version 3.7.4; android plugin - version 0.1
Sonar Android Lint no matching issues found
Very good question! Since your issues originate with FindBugs, you can useFindBugs exclusion filtersto address this. Especially, take a look at the<Method>exclusion. You can specify a regex that matches the method names of your getters and setters in the entity classes, such as<Method name="~_persistence_[gs]et" />Such a filter file can be used by all forms of FindBugs, including the Eclipse plugin and SonarQube. For example, using the SonarQube ant task, you can set the propertysonar.findbugs.excludesFiltersto the absolute path to the FindBugs exclusion file.ShareFollowansweredNov 26, 2013 at 20:32barfuinbarfuin17.1k1111 gold badges8787 silver badges133133 bronze badges1Thanks, this worked perfectly. It looks like Sonar 4 has more options for managing exclusions/patterns from the console but nothing as granular as this.–Shawn SherwoodNov 27, 2013 at 15:05Add a comment|
I'm getting what I think are false positives from FindBugs (2.0.2) and Sonar (3.7.3) on code that is being generated via static weaving of EclipseLink (2.5.1) JPA entities. Specifically, I am seeing multiple occurrences ofES_COMPARING_PARAMETER_STRING_WITH_EQ Comparison of String parameter using == or != in com.test.domain.MyEntity._persistence_set(String, Object)andURV_INHERITED_METHOD_WITH_RELATED_TYPES Inherited method com.test.domain.MyEntity._persistence_get(String) returns more specific type of object than declaredIs there a way to eliminate these warnings for the code generated by EclipseLink without having to globally disable the rules or exclude analysis on the entities entirely?
Is there a way to suppress FindBugs from generating warnings on code generated by static weaving?
you also need to add you build variant folder in pathlike belowproperty "sonar.java.test.binaries", "build/intermediates/classes/test/, app/build/tmp/kotlin-classes/<BuildVariant>UnitTest" property "sonar.java.binaries", "build/intermediates/classes/<BuildVariant>/, app/build/tmp/kotlin-classes/<BuildVariant>/" property "sonar.binaries", "build/intermediates/classes/<BuildVariant>/, app/build/tmp/kotlin-classes/<BuildVariant>/"and one more thing try to avoid using file name with whitespace likelint results.xmlShareFollowansweredJul 29, 2019 at 10:46Archit SurejaArchit Sureja41622 silver badges77 bronze badges1Hi Archit Can you share a sample project with test coverage visible on sonar which shows kotlin classes and test cases are visible on it's dashboard ?–AnkurSep 30, 2019 at 11:46Add a comment|
I am using Jacocov0.8.4and Sonarcubev2.7.1.I am using the following configuration for SonarCube.property "sonar.sources", "src/main/java" property "sonar.binaries","build/intermediates/javac,app/build/tmp/kotlin-classes" property "sonar.java.binaries", "build/intermediates/javac,app/build/tmp/kotlin-classes" property "sonar.tests", "src/test/java" // where the tests are located property "sonar.java.test.binaries", "build/intermediates/javac,app/build/tmp/kotlin-classes" property "sonar.jacoco.reportPath", "build/jacoco/testDevDebugUnitTest.exec" property "sonar.java.coveragePlugin", "jacoco" property "sonar.android.lint.report", "build/reports/lint results.xml"The SonarCube analysis failed with reason as Invalid value forsonar.java.binaries> No files nor directories matching 'app/build/tmp/kotlin-classes'But'app/build/tmp/kotlin-classes'exist in my project folder.But, If I removekotlinthings from the property then it provides the coverage for Java files successfully.Am I doing anything wrong for Kotlin coverage?
SonarQube and Jacoco failed to identify the kotlin-classes directory
The problem is that the SCM plugin wrongly ignore all the files. Disabling the SCP plugin solves the issue.To disable SCP usesonar.scm.exclusions.disabled=trueanalysis parameter.ShareFollowansweredJul 27, 2019 at 3:51Tenusha GurugeTenusha Guruge2,22233 gold badges1818 silver badges3838 bronze badgesAdd a comment|
I have configured a C# project in Sonarqube. After analysis is done, I can see the below screen on the dashboard for the project "CsprojFromCs".When I click on the project name and go to the details page, it shows me "This project is empty" as below.My C# project contains two files and I am able to run it correctly. Why is it showing "This project is empty" in the overview tab?Below is the snapshot of the analysis.1."C:\SonarScanner.MSBuild.exe" begin /k:"CsprojFromCs" /d:sonar.host.url="http://localhost:9000" /d:sonar.login="e1295f619c7ff6f08f974f5a18141b999e830610"Output:2.Command: MsBuild.exe /t:RebuildOutput:3.Command: "C:\SonarScanner.MSBuild.exe" end /d:sonar.login="e1295f619c7ff6f08f974f5a18141b999e830610"Output:
"This project is empty" error in Sonarqube
I solved the problem by deleting my Sonar project that was watching thedevelopbranch. Then I added thedevelopbranch as a long-living branch to the Sonar project analyzing themasterbranch. Before, I had a Sonar project for each long-living branch, because I was using thebranchesproperty intravis.yml(which is getting deprecated now).To add a new branch to Sonarqube you need to add thesonar.branch.nameproperty with the name of the desired branch to thesonar-project.propertiesfile. E.g.:sonar.branch.name=developThen you runsonar-scannerand your branch will be available inside the Sonar-Project.** Make sure to check if the Regex for long-living branches is appropriate to your new branch on Sonarqube. You can't change a long-living branch to a short-living branch or vice-versa after the branch is added to Sonarqube.The result is that I have only one project on Sonarqube now that watches all my branches. It's a lot cleaner and works better.More information on the branch plugin.ShareFollowansweredApr 3, 2018 at 19:50El MacEl Mac3,31377 gold badges4141 silver badges6060 bronze badges2How did you adddevelopas a long-lived branch? I have not been able to do this by editing the RegEx on the "Branches & Pull Requests" section to(master|develop).*–alexvicegrabJan 29, 2019 at 18:05I am not working with Sonarqube at the moment, but is it maybe because of the.before the*? Just guessing... I also had some problems until I got it right, IIRC.–El MacFeb 18, 2019 at 13:34Add a comment|
When I try to analyze my project using sonar-scanner, the scan fails with the following error message:Caused by: Branch does not exist on server: developApparently, this only happens when it analyzes a Pull Request from GitHub. I could reproduce the error, when I add the following configuration tosonar-project.properties:sonar.branch.name = source-branch sonar.branch.target = target-branchWhat could be the cause for this problem?
Sonarqube Branch does not exist on server
I resolved this problem by delete the cobertura jar file in the plugins folder. It seems sonarqube 6.1 does not support cobertura any more. because after i delete the file i can't find cobertura in the sonar plugin management page.ShareFollowansweredOct 30, 2016 at 13:31BirdWyattBirdWyatt4611 bronze badge0Add a comment|
Since I updated my sonarqube server to 6.1 I'm getting this error in my gradle project.I'm using sonar plugin latest version (2.2)classpath("org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.2")anyone knows how to solve it?Thanks!
Unable to register extension org.sonar.plugins.cobertura.CoberturaSensor from plugin 'cobertura'
This is indeed a false positive because, at time of writing, the sonarqube java analyzer (version 4.2.1 at time of writing) does not support cross procedural analysis and so it is not able to determine that indeed, for the condition to be true, the value of minRating has to be non null.This is a feature that we are currently heavily working on to be able to switch off such kind of false positives.ShareFollowansweredOct 15, 2016 at 21:00benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badgesAdd a comment|
I have a sonar alert on this callminRating.getRatgCaam()The alert is related to the sonar rule :Null pointers should not be dereferenced.Ex:AgencyRating minRating = null; ....... if (!getRatingUtilities().isNR(minRating)) { return minRating.getRatgCaam(); //Sonar: Null pointers should not be dereferenced }The methodisNR(minRating)is a helper method that validate among other things, if the object minRating is nullpublic boolean isNR(AgencyRating rating) { return rating == null || isNR(rating.getRatgCaam()); }When I added the not null validation as sonar suggest. Sonar is ok.if (minRating !=null && !getRatingUtilities().isNR(minRating)) { return minRating.getRatgCaam(); // no more alert }Sonar can't determine that the helper method did the null validation. I don't need to do this validation again.Is my case a false positive ?
Sonar false-positive on rule: Null pointers should not be dereferenced
Most of SonarQube language plugins provide a built-in rule to trackNOSONARusage:"NOSONAR" should not be used to switch off issues - This rule raises an issue when NOSONAR is used.(seeJava exampleorlist of equivalent rulefor other languages)Enabling this rule in the relevant Quality Profiles will let you continuously trackNOSONARusage (and potentially take in into account in your Quality Gate).As for getting details on the actual issues that were suppressed, no there is no way toignorea directive that is precisely made toignoreissues.. AsBohemiansuggested you're better off running an ad-hoc analysis with theNOSONARflags removed and see which new issues get raised (avoid doing that on the existing SonarQube project to not add noise to its history).ShareFolloweditedMay 23, 2017 at 10:30CommunityBot111 silver badgeansweredMay 24, 2016 at 6:38Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badges12Thanks. There is noinherentreason the directive made to ignore issues cannot itself be ignored, but that seems to be the current status. I was planning to use a different branch name to preserve history.–Miserable VariableMay 24, 2016 at 13:08Add a comment|
I have to do an audit of the Sonar issues in my project that have been suppressed with//NOSONAR.Is there a way to do a scan thatignoresthe directive so that I can see which violations have been suppressed?
How to ignore //NOSONAR during scan?
From the SonarQube user group:Regarding the support of the decorator construction, it will not be supported by the JavaScript plugin as long as it will not be part of the ECMAScript Standard. Moreover when the JavaScript plugin is not able to parse a file the analysis should not fail, it should succeed but no issue will be reported on the unparsed file.Howeverthere is already a JIRA ticket where you can vote up to show them the need for this feature.JIRA - Support experimental JavaScript featuresShareFollowansweredJul 11, 2016 at 16:25CustodioCustodio8,7741515 gold badges8383 silver badges115115 bronze badgesAdd a comment|
I'm currently using Babel (the Javascript transpiler) which allows me to use the future syntax now. I'm using the decorator functionality (https://github.com/wycats/javascript-decorators). However when I run analysis on that code, SonarQube throws the following error:[09:19:43] 09:19:43.693 ERROR - Unable to parse file: /...../my-form.js 09:19:43.693 ERROR - Parse error at line 10 column 1:1: import {View, Component, Inject, NgScope} from 'app/app'; ... 9: 10: @Component({ ^ 11: selector: 'my-form' 12: }) 13: @View({ 14: template: myTemplate 15: })Will this be covered soon by the Javascript plugin (or at least skipped by the parser but allowing it to continue processing of the file)?. Is there a way to file a JIRA issue for this?
Javascript analysis fail for .js files containing ES7 Decorators
You are totally right in saying that the description here is wrong and then you actually have no way to do not trigger the rule if you want to actually use fallthrough (and thus you might want either to mark issue as false positive in this case or deactivate the rule alltogether)calling the rule "broken" is an opinion so I won't argue on that ;)Nevertheless, a ticket has been created to handle the issue :http://jira.sonarsource.com/browse/SONARJAVA-1169ShareFollowansweredJun 22, 2015 at 13:01benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges2Thanks for creating the ticket. I agree that allowing or forbidding fallthrough is subjective. However, if the aim of S128 is to forbid fallthrough I believe that the documentation should state it more clearly. If not, it would be great to be able explicitly state that a given fallthrough is intended (IIRC it was possible to use a specific trailing comment at some point). Both disabling the rule and marking the issue as false positive fail at making the fallthrough explicit for the reader. [Note: I had prefer to directly contribute on Jira but it seems not possible to create an account]–Clément MATHIEUJun 22, 2015 at 17:27So, and howcanwe achieve a desired/* FALLTHROUGH */(lint for C syntax)?–mirabilosFeb 21, 2017 at 22:55Add a comment|
The rule squid:128 seems to exist to prevent fall-through in switch case unless explicitly stated. It seems a reasonable rule, as forgetting a break is a common mistake.However fall-through are perfectly valid when wanted.The Documentation of this rule states that the only way to achieve a fall-through is to use continuecase 4: // Use of continue statement continue;I have also checked the source code of SwitchCaseWithoutBreakCheck are the implementation really check for "continue" statement@Override public void visitContinueStatement(ContinueStatementTree tree) { super.visitContinueStatement(tree); markSwitchCasesAsCompliant(); }However, the Java language does not support continue in switch/case. Nor the online documentation nor ./java-checks/src/test/files/checks/SwitchCaseWithoutBreakCheck.java are valid Java programs.Am I missing something or is this rule fully broken and prevent using fall-through ?
Sonar, S128: Switch cases should end with an unconditional "break" statement VS continue
Though it is not a direct ans but still here is what I tried and worked for me.Check if SONAR server is reachable. Read the question athttps://stackoverflow.com/questions/20211215to configure/correct the server connectivity issue. Point to note is providingusernameandpasswordand testing the connection.Navigate to your project rootpom.xmlin command prompt.firemvn sonar:sonarResults gets published inhttp://localhost:9000ShareFolloweditedMay 23, 2017 at 12:13CommunityBot111 silver badgeansweredAug 21, 2014 at 8:48fiberairfiberair64177 silver badges1717 bronze badgesAdd a comment|
I Have installed Sonar in my system, and eclipse plugin of the same.I am following below mentioned stepsRunning StartSonar.batGoing to my project directory where POM.XML is located of my project and run the commandmvn sonar:sonarEclipse SonarQuber : Analysis project .I keep on getting error:Unknown version for SonarQube server . Please check server is reachable.And also , sonar analysis is not working from eclipse, I mean if I correct the error indicated by sonar and do sonar analysis again, it shows error at the same.However if I do it from command prompt it is working fine. Please help me on this issue.
Unknown version for SonarQube server (http://localhost:9000). Please check server is reachable
Sonar has added a permission template in Jul 2013.Settings -> Project Permissions -> Permission TemplatesThe project key pattern takes a regular expressionShareFollowansweredOct 22, 2014 at 17:36PortalusPortalus32122 silver badges1414 bronze badges2The option to add "Project key pattern" means automatic association with a regular expression?Thank you a lot for your help!–KrummyOct 24, 2014 at 8:38I believe it only applies to new sonar reports generated.–PortalusApr 21, 2015 at 15:20Add a comment|
i know that i can create User-Groups and add people in here ("Settings" -> Security Section -> "Groups").When I go now to "Project Permissions" and than to the tab "Pattern" I am allowed to create some pattern. I can edit the Pattern Name and wich users / user groups are Administrators, Users or Code Viewers in this pattern.If I switch now back to the projects tab, i can search for Views and Projects, add Permissions for users and usergroups manually or selcet "apply permission template" which will change the settings to the same once like the pattern has got.A small example:Let's say i have to different groups of users. The first group should only be allowed to see code from Project meeting requirements A (e.g. name contains an "A"). The secound group is only allowed to see code from projects containing a name with "B" in it.I can now create the user groups "A-codeviewers" and "B-codeviewers", create templates "A-template" (adding A-codeviewers to the codeviewer section) and "B-template"(adding B-codeviewers to the codeviewer section) and finally select a project -> apply permission template -> A-Template.My Question:Is there a possibility to make this progress automatically? I looking for something like a place where i cann add a regular expression (RegExp) or something like that and if a project key meets the RegExp a specific pattern is used automatically for this project.Thanks for your great help :)
How to enable automatic Project Permissions for Sonar-Users / User-Groups
No, it's not possible to automatically create issues in JIRA. What is your use case / process because I don't think that is worth opening a JIRA ticket for each issue (code formatting for instance)? From my point of view, you should only link important SonarQube's issues to JIRA to make them appear in your release notes for example. Note also that there's a review workflow available in SonarQube:http://docs.sonarqube.org/display/SONAR/Reviewing+IssuesShareFolloweditedJan 19, 2016 at 19:43Tyler Kindy8911 silver badge77 bronze badgesansweredMar 2, 2014 at 21:48David RACODON - QA ConsultantDavid RACODON - QA Consultant3,99311 gold badge1313 silver badges1414 bronze badgesAdd a comment|
I installed the JIRA plugin in Sonar for a project. I can successfully link between issues in Sonar and issues in JIRA using Sonar's web interface and the "Link to Jira Issue" button.The project is mainly a Java project and I use gradle to build and gradle's sonar-runner plugin to do a sonar analysis.Is it possible to have the JIRA issues created ( or solved ) automatically whenever I'm running an analysis , so I don't have to click on "Link to Jira Issue" for every issue ( there's approx 100 issues ).Any help is greatly appreciated.Cheers !
Sonar JIRA Plugin : automatically create / resolve issues
The following discussion covers setting up SonarQube for a javascript project:https://community.sonarsource.com/t/sonarcloud-analysis-for-javascript-application/10591/3I just went through the process for the first time. The key is getting the lcov.info file, which Elena mentioned can be produced by Karma. The following setting causes the coverage info to be published to your SonarQube project:sonar.javascript.lcov.reportPaths=coverage/lcov.infoNote the path is relative to the project root.ShareFollowansweredJan 2, 2020 at 18:27PlantationGatorPlantationGator83511 gold badge1313 silver badges2121 bronze badgesAdd a comment|
I am kinda newbie in using Sonar and plugins for javascript code coverage.Which are the possibilities to find out the quality (including code coverage) of javascript code when analyzed with Sonar?Currently I am using karma runner which delivers a code coverage report. Is it possible to use it in Sonar?Thanks.
javascript code coverage in Sonar
If you want to write a rule engine for the ESQL language, this means that you must first write a parser for this language. And only after you completed this stage, you will create a rule engine based on that parser (with visitor classes that navigate through the AST and that create issues under specific circumstances).You can take a look at how we implemented the Javascript plugin (see the code of version 1.3):the "javascript-squid" module is where the parser is writtenthe "javascript-checks" module is where the rule engine (based on the parser) is writtenthe "sonar-javascript-plugin" module is the actual plugin, which embeds the parser and the rule engine and which provides all the required glue around them.ShareFollowansweredJul 31, 2013 at 7:12Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges1Thank you very much, I will look at that today. My manager has also asked me if its possible to have a plugin which runs multiple regex, which are all stored on one file. Would this be possible has a store of quick and dirty way around it. To begin with I just need to check ESQL statements to ensure it matches up with the clients coding standards–James KingJul 31, 2013 at 8:00Add a comment|
I am creating a new plugin for SonarQube which allows developers to perform static code analysis on ESQL code.Using Maven I can build a shell of a plugin, which produces the JAR file which I can place in the correct folder in order for it to be added to SonarQube.The next stage is to write the Java classes for the rules, however I am unsure on what and where these look like. I am using the example from the following GIT repository:https://github.com/SonarSource/sonar-examples/tree/master/plugins/sonar-reference-pluginDo I simply create a new package with some classes? And how do I actually rules?
SonarQube - help in creating a new language plugin
I'm not sure if this is the report that you want to use but this is the way we have been using to test the report before looking at the commercial edition that has an email feature. We have been using the Sonar PDF Plugin at:http://docs.codehaus.org/display/SONAR/PDF+PluginThis generates a report of the metrics, violations, other details, and then puts these into a pdf which is generated after a sonar analysis. This pdf is located at a static link such as:SonarServer:9000/api/plugins/Pdfreport/getReport?resource=3955You can then use Jenkins to send a weekly, biweekly, monthly, etc email with this link attached. It is a workaround to getting out metrics less often.ShareFollowansweredJul 26, 2013 at 23:28OmerOmer4611 bronze badge11The link doesn't seem to exist anymore.–DivsMay 23, 2018 at 10:34Add a comment|
Is it possible to have Sonar sending periodic (To be more specific, weekly) reports by email? I need to have it analyzing as there are new builds, but report only weekly. Currently i'm running sonar as a jenkins plugin set to analyze whether there is a new build.
Sonar periodic email reports
whenever you callmodel.toString()andyour model is null indeed, then your method will throw aNullPoiunterException.but ifmodel.toString()did not throw aNullPointerEcxeptionthen it's obvious, thatmodel == nullisalwaysfalse...well - that's what SonarQube is trying to tell you...if you want to get rid of the warning you can do whatjensgramsuggested:VALogger.e("SULOD Membership Mapper", ""+model); //implicitly calls toString()ShareFolloweditedOct 17, 2019 at 13:48answeredOct 17, 2019 at 6:24Martin FrankMartin Frank3,44511 gold badge2929 silver badges4848 bronze badges41This. Also, the"" + model.toString()construct is redundant at best; either explicitly cast toString(model.toString(), NPE prone) or do so implicitly ("" + model, NPE safe.)–jensgramOct 17, 2019 at 6:34@jensgram thank you very much - joincodereview.stackexchange.comand help us to create better software =)–Martin FrankOct 17, 2019 at 6:41@jensgram I tried using String (model.toString(), NPE prone) and ("" + model, NPE safe.) but I'm only getting red lines at rone and safe words.–Joana Ma. Lupe GuarinOct 17, 2019 at 9:[email protected] Oh, what I meant was that you should useeitherVALogger.e("SULOD Membership Mapper", model.toString());orVALogger.e("SULOD Membership Mapper", "" + model);. Both will ensure that the second parameter is of typeString.–jensgramOct 17, 2019 at 12:55Add a comment|
In this example below, SonarQube complains thatmodel.toString()isnot nulland (model == null) is alwaysfalse, need some help to understand what can be done to fix it. because the bookmark is initialized as a variable within the if statement and apparently will benull.public static class Mapper implements DataStore.ModelMapper<Membership, MembershipPassDTO> { @Override public MembershipPassDTO mapModel(Membership model) { VALogger.e("SULOD Membership Mapper", "" + model.toString()); if (model == null) { return new MembershipPassDTO(model, "", "", "", "", "", ""); } return new MembershipPassDTO(model, model.getVitalityMembershipId(), model.getMembershipNumber(), model.getCustomerNumber(), model.getVitalityStatus(), model.getMembershipStartDate(), model.getMembershipStatus()); } }
SonarQube implies var is not null
I'm thinking of creating a simple Java application which:Application will keep on listening for requestReceives a REST api URL (some 3rd party address) from caller as requestHits REST api and receives JSON response backForward the response back to original callerMy question is, is it possible within sonarqube?It is possible to add third party library into a Custom SonarQube Plugin. You can create tasks in which you can do whatever you implement.Supposing, it is possible: Second question - I’ve gone thru sonarqube documentation, but I’m not able to pinpoint which plugin class to use. Should I use PageDefinition only?You should implementWebService Extension Pointwhich allow you to extend SonarQube web API and add new bahaviours on requests.PageDefinition is a way to add some web pages on the WebUI.ShareFollowansweredAug 1, 2018 at 14:41begarcobegarco75677 silver badges2121 bronze badgesAdd a comment|
I've a requirement to develop acustom sonarqube pluginthat will act as a proxy service.I'm thinking of creating a simple Java application which:Application will keep on listening for requestReceives a REST api URL (some 3rd party address) from caller as requestHits REST api and receives JSON response backForward the response back to original callerMy question is, is it possible within sonarqube?Supposing, it is possible: Second question - I’ve gone thrusonarqube documentation, but I’m not able to pinpoint which plugin class to use. Should I use PageDefinition only?Please suggest.ThanksP.S. - Similar question was posted onsonarqube community, posting it here for broader audience.
Custom sonarqube plugin - proxy service
+50the sonar server name / details needs to be checked. not sure if you are using the plugin or sonar runner for execution. either ways validate the sonar.host.url value and ensure it mapped to the correct hostname and port.ShareFollowansweredAug 24, 2018 at 15:17Ashokekumar SAshokekumar S36133 silver badges88 bronze badgesAdd a comment|
I have SonarQube Server and Jenkins instance running on Windows machine.I have created Jenkins job to generate Code Coverage Report with SonarQube. This job runs on Linux machineBuild CodeRun Unit Test-CasesRun Sonar ScannerBut later I get error in jenkinsERROR: Error during SonarQube Scanner execution ERROR: Unable to execute SonarQube ERROR: Caused by: Fail to get bootstrap index from server ERROR: Caused by: Failed to connect to localhost/0:0:0:0:0:0:0:1:9000The error is right as my server is running on Windows machine and not on linux (127.0.0.1).Want to know that how to resolve this?and get result on Windows. Is it possible ?
Error in SonarQube Scanner Execution [Windows - Linux Master-Slave]
In case anyone stumbles upon this question, it turned out to be a bit of a red herring!Following some good discussions with colleagues we were all in agreement that acoveragegate condition withOver Leak Periodset to always was an incorrect gate configuration.I was under the false assumption that the SonarQube way was the built-in default and was not editable. It turns out however, that the gate is in fact editable.Read-onlymode was only enforced from v7.0 onwards as perrelease notes. So the root cause of our misconfiguration is still under investigation but we can be sure that it's not the default and recommended Gate as per SonarQubedocumentationIn the example posted above, the gate complains that the additional 0.7% coverage is below the minimum 40% error level. The condition itself is applying as configured but it really should be impossible to enable leak period for coverage. Instead theCoverage on New Codeshould be used.So the simple one liner solution: Make sureOver Leak Periodis set to never (and/or not selected) if using theCoverageconditionShareFolloweditedJul 18, 2018 at 17:28answeredJul 18, 2018 at 16:44Franko_KFranko_K8188 bronze badgesAdd a comment|
Maybe this is my ignorance in understanding the Quality Gate, but I have a failing quality gate due to the default 40% Coverage over leak period when using the sonarway code quality gate via VSTS build. The issue is that there has been no modifications to the code between the initial analysis and the latest analysis, so to reference the metaphor in the docs.. there is no additional water in the kitchen.. hence I am not seeing a reason for this criterion to be failing.Has anyone else experienced this and/or can anyone explain the logic if this is indeed the expected behavior? IMO, I would expect the Leak Period Code Coverage check to not apply when no modifications have occurred on the code base during the leak period.My SQ analysis is being executed via VSTS and the version of SQ is 6.7.3.Summary of Analysis with failing QG due to coverage leak (also the percentage coverage is still the same)The issue also occurs when there are code modifications and those specific modifications have 100% code coverageThe sonarway quality gate configuration is as follows (default configuration):As requested, I have also created a simple demo project which also demonstrates the behavior (running builds with SQ analysis and the second build fails due to 0.0% coverage over leak period although there is no new code). Sample project can be foundhereAppreciate if someone can explain this behavior to me as it seems contrary to the documentation.
SonarQube - Sonar way Coverage over leak period fails even when no modifications occur on codebase
get method namepublic class SomeClass extends IssuableSubscriptionVisitor { @Override public List<Tree.Kind> nodesToVisit() { return ImmutableList.of(Tree.Kind.METHOD); } @Override public void visitNode(Tree tree) { MethodTree methodTree = (MethodTree) tree; IdentifierTree methodName = methodTree.simpleName(); // getName from methodName. } **get invocation method name** public class SomeClass extends IssuableSubscriptionVisitor { public static IdentifierTree methodName(MethodInvocationTree mit) { IdentifierTree id; if (mit.methodSelect().is(Tree.Kind.IDENTIFIER)) { id = (IdentifierTree) mit.methodSelect(); } else { id = ((MemberSelectExpressionTree) mit.methodSelect()).identifier(); } return id; }ShareFolloweditedMar 26, 2018 at 8:34answeredMar 23, 2018 at 12:37Josef ProchazkaJosef Prochazka1,27322 gold badges99 silver badges2828 bronze badges3Can you clarify what I am meant to @Override, from my understanding in the super class their is no nodeToVisit() or visitNode() to be overridden?–Jordan SmithMar 25, 2018 at 21:23It is a class extending SubscriptionVisitor, if you need to use BaseTreeVisitor you can overide public void visitMethodInvocation(MethodInvocationTree tree) or public void visitMethod(MethodITree tree)–Josef ProchazkaMar 26, 2018 at 7:59Thank you very much for the help–Jordan SmithMar 27, 2018 at 4:57Add a comment|
Trying to extend the below linked Sonarqube rule to ignore the occurrence of a string literal in a logger method.I am having issues trying to extract method names for methods (which in the context of the Base Visitor Tree may not be scoped as methods from my analysis. But have had some luck looking at methodInvocation type to extract a few method names).So my question is does any one have a definition list of the Base Visitor Tree elements and how it would see different statements?e.g. weeLogger.Log(exception, "exception occurred");ore.g. logger(exception1, "exception occured);And as well has anyone done anything similar and share how they extracted out method names from the Base Visitor Tree class for analysis with Sonarqube?https://github.com/SonarSource/sonar-java/blob/master/java-checks/src/main/java/org/sonar/java/checks/StringLiteralDuplicatedCheck.java
Sonarqube Custom Rule- String Literal should not be duplicated, ignored in context of logger
Based on the 'C: Label' in your screenshot this seems to be running on Windows OS. If so you may be impacted by:SONAR-9734-temp storage grows on Windows due to cache under temp/ce not cleaned upShareFollowansweredAug 18, 2017 at 15:06Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badges2Yes, that accurately describes my problem. Thanks for linking me to this Nicolas. I see that it is currently n progress. I'll watch the issue to keep an eye on it.–ASnyderAug 18, 2017 at 21:48@ASnyder : issue will be fixed in SonarQube v6.6 , you should accept this answer so it can benefit to other users experiencing similar symptoms–Nicolas B.Aug 28, 2017 at 11:26Add a comment|
Our SonarQube 6.0 instance has a "sonarqube-6.0/temp/ce" folder than contains 35.9GB of data. The oldest data in that folder is almost 3 months old. A graph of disk space usage over time is shown below.This postsuggests that this was fixed in SonarQube 5.1.2, andthis postsays that it's fixed in SonarQube 5.2. We are running SonarQube 6.0.How can I configure SonarQube to automatically cleanup the temp directory to remove unnecessary files so that the server doesn't run into disk space issues?
Why does SonarQube 6.0 temp folder have large amount of old data in it (36GB total)?
With the output you have posted it seems you are using dotnet commanddotnet buildordotnet msbuild.According to this linkhttps://www.sonarsource.com/resources/product-news/news.html#2017-04-13-sonarqube-scanner-for-msbuild-2-3-releasedsonarqube-scanner-msbuild supports only MSBuild 15 or later.So try usingmsbuilddirectly instead ofdotnetcommand. If you are doing this in a ci environment you may need to installmsbuild tools 2017. Download is located at the bottom of the page.Also, make sure you are usingsonarqube-scanner-msbuildShareFollowansweredSep 10, 2017 at 5:02nandithakwnandithakw9991111 silver badges1616 bronze badgesAdd a comment|
I am trying to make use of SonarQube task targeting dotnetcore solution, but the within the solution there are a couple of projects that use dotnetstandard framework. So when attempting to analyze the code, the new SonarQube task throws an error stating that it is unable to locate Microsoft.Build.Utilities.v4.0 as shown below:2017-07-26T20:33:04.5685747Z [C:\agent\_work\6\.sonarqube\bin\targets\SonarQube.Integration.targets(166,5): error MSB4062: The "IsTestFileByName" task could not be loaded from the assembly C:\agent\_work\6\.sonarqube\bin\SonarQube.Integration.Tasks.dll. Could not load file or assembly 'Microsoft.Build.Utilities.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask. [C:\agent\_work\6\s\PSG.Identity.Contracts\PSG.Identity.Contracts.csproj]2017-07-26T20:33:05.1623435Z ##[error]Error: C:\Program Files\dotnet\dotnet.exe failed with return code: 1The IntegrationTest project is written on dotnetcore framework, but that project references 2 projects that are written on dotnetstandard framework. Is it possible to have this task support multiple frameworks?
Is SonarQube VSTS Task version 3.0.1 unable to support multiple msbuild types?
We had the same issue, within our company, and the only solution was to use the deprecated attributesonar.profile(https://docs.sonarqube.org/display/SONAR/Analysis+Parameters).Sidenote: Generally there is also a interesting view on how to analyze branches. The general recommendation from sonarSource suggests to only use preview modes for short living branches. As a fact bitbucket-plugins with a richer featureset than just commenting issues, sadly need branch based analysis.https://jira.sonarsource.com/browse/SONAR-5370- the property will be removed in 4.5.1 based on the sonar taskShareFolloweditedJun 13, 2017 at 23:00answeredJun 13, 2017 at 22:07Simon SchrottnerSimon Schrottner4,42611 gold badge2525 silver badges3939 bronze badges2yes, this is our situation (trying to include Sonar stats with BitBucket pull requests and Bamboo to launch Sonar analysis on commit). I'd be happy to switch to using the preview mode but I don't see a way to do that with the existing plugins as you say.–MzzzzzzJun 14, 2017 at 13:511something on the side, i dont know, how many builds you plan to trigger, but as code analysis may take some time, you probably want to trigger it by hand withmarketplace.atlassian.com/plugins/…- we only trigger the "Feature builds" on "Open, Reopen, and by trigger button" - can save you some jenkins resources :D–Simon SchrottnerJun 14, 2017 at 13:56Add a comment|
Our use case for Sonar creates new Sonar projects for each branch of our repository. How do we automatically associate the new branch project with a (non-default) Quality Profile and Quality Gate?We're running this in a Maven project if that's relevant.
Automatically associate new Sonar project with custom quality profile and quality gate
FYI the release the SonarQube Scanner for Gradle 2.1 should happen very quickly and this version includes the support of Gradle 3.X. Seehttps://jira.sonarsource.com/browse/SONARGRADL-16which is already fixed.ShareFollowansweredAug 25, 2016 at 12:08Freddy - SonarSource TeamFreddy - SonarSource Team2,84011 gold badge1515 silver badges1313 bronze badgesAdd a comment|
I am setting up a new multi-module gradle project to be built in jenkins and trying to get sonarqube analysing it but I have struck several incompatibility issues which I haven't been able to resolve.I am looking at usingthe sonarqube plugin because our existing projects get a warning about the deprecation of sonar-runner: The 'sonar-runner' plugin has been deprecated and is scheduled to be removed in Gradle 3.0. please use the official plugin from SonarQube (the docs).gradle 3this simple example from sonarqubehttps://github.com/SonarSource/sonar-examples/blob/master/projects/languages/java/gradle/java-gradle-simple/build.gradleIf I use gradle 3 I get this error: org.gradle.internal.jvm.Jvm.getRuntimeJar()Ljava/io/File;If I use gradle 2.14 I get this error: Caused by: java.io.IOException: Incompatible version 1007 This error in the past has been caused by an incompatibility between the jacoco and sonarqube plugins seeJaCoCo SonarQube incompatible version 1007.Which versions should I use?
which versions of gradle, sonarqube and jacoco plugins are compatible