Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
Here are some tutorials on setting up custom rules on PMD, I use PMD integrated with Maven myself in addition to sonar.http://www.techtraits.com/Programming/2011/10/31/writting-pretty-code-with-pmd/http://www.techtraits.com/Programming/2011/11/05/custom-pmd-rules-using-xpath/http://blog.code-cop.org/2010/05/custom-pmd-rules.html
|
At present I am working for a group where source code (Java) for multiple projects have to be analysed by static code analysic toolsBut I would like to write custom rules that I can add to the existing set of rules provided by the tool (the rules would involve mostly regular expressions matching for text/string within the source code).Especially keeping the perspective that I should be able toeasily write/add my own custom rulesthat can be used alongwith the existing list of rules of the tool.Can anyone please suggest which tool (or combination of tools) among the below given list should I use ?PMDCheckstyleFindbugsEdited : ThanksIrafor the direction. I am looking for static code analysis tools to be used along with Sonar. I hope now the question is clear.
|
Ease of writing custom rules in (Java) static code analysis tools
|
No, this is not possible yet. You can ask for this feature and discuss it on the Sonar user mailing-list.
|
Is it possible in sonar to transfer "false positives" between branches?This is our workflow: we develop in branch 1, we do our sonar checks on this branch, when branch 1 will be released, we merge this into the trunk, then we create branch 2 from the trunk, and we do our sonar checks on branches2.This "branch 2" is a new sonar project (it can't be the same because we sometimes have 2 branches open at the same time and also 2 sonar projects). But this "branch 2" sonar project has lost all the "false positives" marks.How can we keep the false positives between 2 branches?
|
How to keep false positives in sonar between branches?
|
Seehttps://javaalmanac.io/bytecode/versions/for Java Class File versions.Your error tells you, that you are using JDK 8 (52.0) but the plugin code was compiled with JDK 11 (55.0). So your JDK is unable to understand the plugin classes.What to do? Change the JDK with which you execute the maven build to JDK 11. Your source code can still be java 8 and you can also compile for jdk8 - but the excuting JDK must be 11+.
|
My Java project written and compiled in 1.8 through Maven. I am getting the following error when I try to analyze my code using sonar-maven-plugin Ver. 3.9.1.2184 for SonarQube 9.2.4.The following parameters are mentioned.sonar.java.jdkHome=D:....\jdk1.8.0_121
sonar.java.source=1.8Execution default-cli of goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar failed: An API incompatibility was encountered while executing org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar: java.lang.UnsupportedClassVersionError: org/sonar/batch/bootstrapper/EnvironmentInformation has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
[ERROR] -----------------------------------------------------
[ERROR] realm = plugin>org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
[ERROR] urls[0] = file:/../.m2/repository/org/sonarsource/scanner/maven/sonar-maven-plugin/3.9.1.2184/sonar-maven-plugin-3.9.1.2184.jar
[ERROR] urls[1] = file:/../.m2/repository/org/sonatype/plexus/plexus-sec-dispatcher/1.4/plexus-sec-dispatcher-1.4.jar
[ERROR] Number of foreign imports: 1
[ERROR] import: Entry[import from realm ClassRealm[maven.api, parent: null]]
|
Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar error
|
As per the documentationhere, it says SonarQube only supports JDK11 (Oracle or OpenJDK)
|
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed4 years ago.Improve this questionI am currently using SonarQube Community Edition version 7.7 on Java 8 JDK using Maven, Iwant to start evaluating OpenJDK 13 . Sonarqube doesn't support OpenJDK 13
|
is there any compatible version of SonarQube with Java 13 [closed]
|
According toSonarsource rules explorer:Fields in a Serializable class must themselves be either Serializable
or transient even if the class is never explicitly serialized or
deserialized. For instance, under load, most J2EE application
frameworks flush objects to disk, and an allegedly Serializable object
with non-transient, non-serializable data members could cause program
crashes, and open the door to attackers. In general a Serializable
class is expected to fulfil its contract and not have an unexpected
behaviour when an instance is serialized.However as you've said theLocalDateTimeis serializable. This means that sometimes Sonar rules are not good (when using Hibernate with Objects that contains LocalDateTime which is Serializable).Onesolution would be to use your own rules instead of Sonar default ones.Anotherone (this is a workaround more than a solution) would be to annotate your field with :@SuppressWarnings("squid:S3437")
|
I've got a sonar plugin to Eclipse, and it's giving me aMake this value-based field transient so it is not included in the serialization of this classon a LocalDateTime object. What I do not get is, LocalDateTime is definitely serializable. Here's the classpublic final class LocalDateTime
implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable {Anyone have any ideas? Do I just not understand what transient means? Normally I wouldn't pay much attention, but I'm weirdly able to serialize it in a Get request, but not deserialize it in a post request and I'm wondering if it's related to this.
|
Why does Sonar want a LocalDateTime marked transient when it's already serializable?
|
that sure are lot of modules. not sure if it is best practice or if you have already tried this but,u can configure plugin execution using profiles.also each profile will include very related set of modules for such buildnow select profile one after another in required order to build.Ref -http://maven.apache.org/guides/introduction/introduction-to-profiles.htmltaken from below stackoverflow postIn Maven, how to run a plugin based on a specific profile
|
I'm working on one fairly big project (around maven 550 modules). Now, I was wondering how to run sonar on such a big project at the level of CI (we use Jenkins for this)If we runmvn sonar:sonarout of parent pom folder, it runs for ~1 hour and then just fails on OutOfMemory even if we increase it significantly (~16GB)So, we examine other strategies of running sonar. Currently the most appealing ideas are:Run sonar for each module during the lifecycle.Maintain the list of (sub)modules for which the sonar should be run in parallel during the post build phase.So, I would like to ask what is the best way to run sonar for such a big project? Could someone please provide some generic configuration for implementing the first or second idea or describe any other way/best practices?
|
Using sonar on big projects
|
Unfortunately, there's currently no plugin that we are aware of and that analyzes SCSS files.Note: Since SonarQube 4.2, multi-language projects are supported so you can analyze your CS, JS and CSS files all at one. SeeAnalyzing a Multi-Language Project documentation.
|
I have a TeamCity-SonarQube setup. I use TeamCity to execute sonar-runner and push the result to a local SonarQube instance. Its a .NET/C# solution and we are moving towards SASS especially SCSS. My current configuration analyzes .cs, .js, and .css files separately using the sonar.language configuration. Is there any support for scss (sass in general). Its an issue since sonarqube does not ingest xml results from jshint, csshint and other lints. I have a SCSS-LINT setup to lint .scss files in my solution but I cant find a SonarQube plugin for scss or any way to integrate the scss-lint result with SonarQube.My question: Is there a way to analyzes .scss files and display the results in SonarQube as well as configure quality gates etc on it ?
|
SonarQube analysis of scss/sass files?
|
I think that you need to develop a new Sonar Plugin. Take a look at the following links that might help you.http://docs.codehaus.org/display/SONAR/Developing+Pluginshttp://docs.codehaus.org/display/SONAR/Plugin+hostingDigging around, I found this closed Sonar issue suggesting that Sonar'sJavascript pluginworks better, compared to jsLint:SONARPLUGINS-1829
|
jsHint and cssLint can output their results in to standard xml (sjlint.xml and csslint.xml format) file.Is there a way to display those results with sonar?What I'm trying to do is to run a jenkins job that will run validations on java script and show the results in Sonar.Thank you.
|
displaying jsHint and cssLint results in sonar
|
According to this, it could be linked to using Derby, the only proposed solution is using a stronger db instead.Following comments from sinbadblue here are links to discussions with answers from sonar team members which suggest 2 known reasons for execute decorator to be slow :Using derbyHaving the database server on a different network from the analyzerHere are the links2010http://comments.gmane.org/gmane.comp.java.sonar.general/49022011http://sonar.15.x6.nabble.com/Sonar-slow-in-quot-Execute-Decorators-quot-td3187847.html2012http://sonar.15.x6.nabble.com/Sonar-analysis-remains-on-Execute-Decorators-for-Net-Applications-tp4514700p4515249.htmlThe database is not always the issue but these 2 should definitely be checked before further investigation.
|
I was just analyzing our (1 main/ 3 sub) project and wanted to analyze the code with my local Sonar server by typingmvn sonar:sonar(after cleaning and packaging the project(s)).It successfully analyzes the EJB project but in the phaseExecute decorators ...it takes forever to complete (around half an hour). This makes the analysis of the project very slow. What is going on in that phase and how can I improve the speed?Best regards,
SebastianVersions used:Maven 3.0.3Sonar 2.10
|
"Execute decorators" phase takes forever
|
Well, you can replace:if (divisionId != other.divisionId)
return false;
return true;with the equivalent:return divisionId == other.divisionId;This will returnfalseifdivisionId != other.divisionIdandtrueotherwise.
|
While solving sonarQube issue i face the below warning,does any one tell me how to overcome this warningMethod:-@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Division other = (Division) obj;
if (divisionId != other.divisionId)
//getting warning for above if condition
return false;
return true;
}Warning :Replace this if-then-else statement by a single return statement.Description:-Return of boolean literal statements wrapped into if-then-else ones should be simplified.
|
Replace this if-then-else statement by a single return statement
|
SonarQube (formerly just "Sonar") is a server-based system. Of course you can install it on your local machine (the hardware requirements are minimal). But it is a central server with a database.Analyses are performed by some Sonar "client" software, which could be the sonar runner, the sonar ant task, the sonar Eclipse plugin etc. The analysis results can be automatically uploaded to the server, where they can be accessed via the sonar Web application.In an environment with many developers, you should run a build server (e.g. Hudson or Jenkins), which performs automatic sonar analyses as part of the nightly build. Other schedules are possible, but the developers should know when they can expect updates of the server-side analysis results. The results of the automated analysis can be displayed in the individual developer's Eclipse editor by way of the sonar Eclipse plugin.The architectural documentation on Sonar is quite sparse. I've looked for a picture to visualize what I just described, but could not find one ...
|
I have a simple problem, with a simple answer probably, but I can't find what is it. We want to deploy SonarQube along with Checkstyle and some other tools, but we can't find out is it meant for a centralized, server deployment, or on each developer machine? All tutorials show installations on separate machines and being used in the localhost, while there is a public instance example, and the requirements and specs certainly look service-like.On the other hand, I'm not getting how do the developers submit their code for checks if it is on a server.So, in short, how is it deployed? Any checklist or something similar would be of great help.
|
SonarQube - how is it used
|
UsingSonarQube Scanner for Jenkins 2.8.1the solution is available out of the Box:stage('SonarQube analysis') {
withSonarQubeEnv('My SonarQube Server') {
sh 'mvn clean package sonar:sonar'
} // SonarQube taskId is automatically attached to the pipeline context
}
}
stage("Quality Gate"){
timeout(time: 1, unit: 'HOURS') { // Just in case something goes wrong, pipeline will be killed after a timeout
def qg = waitForQualityGate() // Reuse taskId previously collected by withSonarQubeEnv
if (qg.status != 'OK') {
error "Pipeline aborted due to quality gate failure: ${qg.status}"
}
}
}
|
Within my Jenkins Pipeline I need to react on the SonarQube Quality Gate.
Is there an easier way to achieve this but looking in the Sonar-Scanner log for the result page (e.g.https://mysonarserver/sonar/api/ce/task?id=xxxx) and parse the JSON Result from there?I use Jenkins 2.30 and SonarQube 5.3Thanks in advance
|
How to react on SonarQube Quality Gate within Jenkins Pipeline
|
If you're using Yosemite (like I am) you must set environmental variables this wayCreate new file at ~/Library/LaunchAgents/environment.plistAdd this code block and modify to appropriately set your environmental variables<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>my.startup</string>
<key>ProgramArguments</key>
<array>
<string>sh</string>
<string>-c</string>
<string>
launchctl setenv JAVA_HOME /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home
launchctl setenv M2_HOME /Users/chrismanning/apache-maven-3.2.5
</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>Save and restart your computer. This is the proper way to load Yosemite environmental variablesIf you are using an older version of Mac OS X, see this answerSetting environment variables in OS X?
|
My maven build works fine in IntelliJ IDEA. That is not the issue. The issue is relating to SonarQube Community Plugin.ERROR 17:08:38.358 > java.io.IOException: Cannot run program "mvn" (in directory "/Users/chrismanning/Projects/Registry/registry/idea-files"): error=2, No such file or directoryLocal analysis script:mvn sonar:sonar
-DskipTests=true
-Dsonar.analysis.mode=issues
-Dsonar.scm.enabled=false
-Dsonar.scm-stats.enabled=false
-Dissueassignplugin.enabled=false
-Dsonar.preview.excludePlugins=emailnotifications,issueassign
-Dsonar.report.export.path=sonar-report.jsonI definitely have maven installed and in my path. (it's symlinked in /usr/local/bin)chrismanning@Chriss-MacBook-Pro:~/Projects/Registry/registry/idea-files$ mvn -version
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T12:29:23-05:00)
Maven home: /Users/chrismanning/apache-maven-3.2.5
Java version: 1.8.0_40, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.10.3", arch: "x86_64", family: "mac"M2_HOME and PATH are propely defined in /etc/launchd.conf
|
SonarQube Local Script in IntelliJ can't find mvn (IOException/No such directory)
|
That's a bug in SonarQube. It's overgeneralizing thesun.*package as mentioned inWhy Developers Should Not Write Programs That Call 'sun' Packagestocom.sun.*package. This is incorrect. Oracle didn't mean to say that in abovelinked article. SonarQube should really only penalize usage ofsun.*package or whatever is internally used by an arbitrary JRE/JDK implementation. Thecom.sun.*package is not JRE/JDK API/impl related at all.Either turn off the S1191 rule, or mark all hits oncom.sun.*as false positive.See also:What is inside com.sun package?SonarJava issue 437
|
I have a J2EE project with the following characteristics:CDI 1.0
Dynamic Web Module 3.0
Java 1.7 (it's being changed to 1.8)
JSF 2.0
JPA 2.0I'm running SonarQube 5.6.6 rules against it and it felt into the ruleClasses from "com.sun." and "sun." packages should not be usedsquid : S1191Classes in com.sun.* and sun.* packages are considered implementation details, and are not part of the Java API. They can cause problems when moving to new versions of Java because there is no backwards compatibility guarantee. Such classes are almost always wrapped by Java API classes that should be used instead.because I'm using classescom.sun.faces.application.ApplicationAssociateandcom.sun.faces.application.ApplicationResourceBundle.I've seached another threads about this and most of them say I should change the rule to exclude the specific package or class.I think there is no point in simply circumvent the rule, so I would like to know if there are actualy java API (1.7 or 1.8) classes for these sun classes.If not, I believe it's better to keep the alert until java API classes become available for these sun classes.Any tip/advice on this?
|
SonarQube rule Classes from "com.sun.*" and "sun.*" packages should not be used
|
You can use the REST API, to query the data into JSON text and then export that JSON to a CSV file.I used the command below to get a JSON response:http://xxxxx.xx.xxxx.com:9000/api/issues/search?componentRoots=test_xxx_xx&statuses=OPEN,REOPENED&pageSize=500&pageIndex=1WherecomponentRootsis the your sonar project name.It gave all the issues in JSON and then I converted it in to a CSV.
|
Is there a way to export Sonarqube reports into Excel - based on major, minor and critical categories?
|
Exporting Sonarqube reports into Excel - based on major, minor and critical categories
|
Your concatenation will be done before the condition check in the logger. So if you call the logger 10 times and the evaluation returns false, your strings will be concatenated 10 times too with no reason. The logger will handle all concatenation and formatting after it's evaluation is passed and it needs to print something, that way you're saving up on useless operations.LOGGER.error("Cannot load object in status {} ({})", status, statusDescription, e);
|
Our company just started a sonar farm. I was curious about our code quality and wanted to improve.I have a code containing such logger calls:LOGGER.error(String.format("Cannot load object in status %s (%s)", status, statusDescription), e);
LOGGER.info(String.format("%s object(s) loaded in status %s (%s)", objects.size(), status, statusDescription));Sonar triggers rule squid:S262, Invoke method(s) only conditionally"Preconditions" and logging arguments should not require evaluation. Rule triggered by both theses lines.About this one, I'm not really sure to understand what's going on. The explanation seams not well fitting to my use case. Sonar doc provided this example:logger.log(Level.DEBUG, "Something went wrong: " + message); // Noncompliant; string concatenation performed even when log level too high to show DEBUG messageswhich I perfectly understand (debug will not be logged in production, thus unnecessary operations will occurs). But for info and error level, I would assume that you want to log it anyway. Moreover, in my case, I want both to be logged.Which is the good approach ?
Rewrite differently not using String.format ? Tune sonar to not fire on info/error level ? Just ignore sonar on this one ? Something else ?
|
Sonar violation: Invoke method(s) only conditionally
|
I solve it moving the "coverageReporters" configuration from "jest.config.js" at root folder to "jest.config.ts" at project folder, and in lcov configuration I set:coverageReporters: ['html', ["lcovonly", {"projectRoot": __dirname}], 'text-summary'],setting the projectRoot to __dirname make the "SF" path relative again.
|
I'm running an Angular project with an @nrwl/nx setup and Jest for unit tests. I have configured Jest to generate lcov files for each app and lib, which are then picked up by SonarQube Scanner to report the test coverage. Each lib is its own Sonar module.Recently I updated my Jest version from 24.1.0 to 25.1.0. Since then my coverage in SonarQube is always at 0%, because the scanner is unable to find the files:WARN: Could not resolve 1 file paths in [/mnt/c/Users/Patrick/Projects/projectname/apps/projectname/../../coverage/apps/projectname/lcov.info], first unresolved path: apps/projectname/src/environments/environment.tsI analyzed the lcov files with both version and I noticed that the generated path changed.Jest 25.1 (does not work)SF:apps/projectname/src/environments/environment.tsJest 24.1 (works)SF:/mnt/c/Users/Patrick/Projects/projectname/apps/projectname/src/environments/environment.tsWhen I change it manually to the following, this also works:SF:src/environments/environment.tsBut now I'm stuck a little bit, because I did not find a way to tell Jest to generate the path the old way or tell Sonar that the path is now a different one.
|
Since Jest 25, coverage reports are having a different source path
|
Covered inworkflow:rulestemplates, In this case, you can use theCI_OPEN_MERGE_REQUESTSvariableto determine whether to run the pipeline for merge request or just the feature branch.If you use both [pipelines for merge requests and branch pipelines], duplicate pipelines might run at the same time. To prevent duplicate pipelines, use the CI_OPEN_MERGE_REQUESTS variable.Usingworkflow:rulesyou can do this for the entire pipeline, but the same principle can also be applied to individual jobs.workflow:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS'
when: never
- if: '$CI_COMMIT_BRANCH'This means your pipeline will run:for merge requestsfor branch pipelines UNLESS there is an open merge requests
|
I want to see sonar results in the MR(merge request) command section when I create a MR.My main expectations:if there is an existing MR for the source branch, trigger detached pipeline (do not trigger feature pipeline. I need only that one for reviewing sonar results in MR commands)if there isn't an existing MR for the source branch, just trigger the normal feature(source) branch pipelineI tried to do it with the below example stage. But when I pushed the commit to the source pipeline, while MR is exist for source branch. I still getting double pipeline. Detach and source pipelines are running and I don't want to see both in same time, plus except not working with rules configuration. How can I integrate except section with rules part.This is my gitlab-ci stage:deploy:
stage: deployment
when: manual
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CUSTOM_VARIABLE == "true" || $CUSTOM_VARIABLE == "true"'
script:
- ....
- ....
except:
- tags
- mainI also tried below rules, if one of them fit my condition don't run the other one. But it still trigger both pipelines.deploy:
stage: deployment
when: manual
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CUSTOM_VARIABLE == "true"'
when: on_success
- if: '$CI_PIPELINE_SOURCE == "push" && $CUSTOM_VARIABLE == "true"'
when: on_success
script:
- ....
- ....
except:
- tags
- main
|
Gitlab-ci: if MR exist just trigger merge_request detach pipeline, if not trigger source branch pipeline. Those 2 pipelines shouldn't run in same time
|
By default, SonarQube detects duplications at 4 levels:Within a source fileAcross multiple files in a projectAcross modules of a projectAcross multiple projectsYou can turn the last one off globally or at the project level:Administration > General > Duplications > Cross project duplication detectionHowever, you might not want to do that. The point of detecting cross-project duplications is to help you recognize opportunities to pull shared code out into libraries. Because after all duplications turn into a maintenance nightmare: when a change is needed, you have to make itntimes innplaces, and changentests.
|
I have a set of projects the have lot of code in common. SonarQube displays a high percentage of duplication. When I go to see the duplication per file, the references on the duplicated code point to the other projects code where the code is the same. Is there a way to have duplication only run against the same project?
|
SonarQube is adding duplications when code is repeated in other projects besides the one under analysis
|
Very old post but may help someone. I had similar issue and below configuration worked for me:sonar.sources=src/main/java
sonar.java.binaries=target/classes
|
I'm trying to upload my project to a remote sonarqube server.This is the command I run sonar scanner:sonar-scanner -Dsonar.projectKey=my-project -Dsonar.host.url=https://xxxx:9000 -Dsonar.login=the-secret-key -Dsonar.java.binaries=**/target/classesbut it throws the error on java.binaries.INFO: Configured Java source version (sonar.java.source):
none
INFO: JavaClasspath initialization
ERROR: Invalid value for sonar.java.binaries
INFO: ------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------
INFO: Total time: 20.276s
INFO: Final Memory: 10M/161M
INFO: ------------------------------------------------------
------------------
ERROR: Error during SonarQube Scanner execution
No files nor directories matching **/target/classesI tried different values like ./target, /target/, /target/classes (where the jar is being stored). However, I am encountering this error of not found. (even though the directory exists)By running sonar:sonar on my IDE and maven sonar:sonar on my terminal would send over the result to sonarqube, but my goal is to include this command in my jet-steps
|
Sonarqube invalid value for java binaries
|
You're close,sonar.projectNameis what you're looking for. Have a look at this documented list ofAnalysis Parameters.Note that some SonarQube Scanners have specific behaviours, for example:the scanner for Maven will in any case take values from the project definition itself (e.g.sonar.projectNameis the project's<name>attribute)thescanner for Gradledefaults toproject.nameBut when using the standard Scanner (sonar-runner) it's indeed a good idea to keep things under control by explicitly settingsonar.projectName.
|
With each project created at my company, a new naming convention is used in Sonar. So some projects have their name as abbreviated, and some have their names as camel case, and some projects just have their names as words with spaces.If we could passsonar-runneraproject-nameparameter, then that would let us have these values set by the integrations team (2-3 people), instead of the head of each project (10+ possible people).I feel like this may force us to create a Sonar rule for sonar properties, which is entirely too meta.Is it possible to call something likesonar-runner --rootProject='my project'and have it? I already triedsonar-runner -DprojectName=$name.
|
Is it possible to tell Sonar the project name from the command line?
|
sonar.web.host=127.0.0.1I think this is the problematic line in your conf. This line indicates which IP address the Web Server will bind to. If you set it to127.0.0.1, then Server will only respond if you reach to it through the IP127.0.0.1, that is, you'll only be able to access it fromlocalhost, thoughIPv4. (Your browser will probably prefer IPv6, with::1being the host)Comment out the line (prepending a#) in order to have it listen to every IP the machine is called by.If you can verify access from the host machine itself, but the above doesn't help, then you might want to check if your firewall is blocking requests.
|
I am trying to access Sonar through web browser. I already started it on my terminal but when I try to access it on web browser through , it shows nothing. However, the status shows Sonar is running. How can I make it running on the web browser ?The configuration for Sonar web is:sonar.web.host=127.0.0.1
sonar.web.context=/sonar
sonar.web.port=9000
|
SONAR not working on Web Browser
|
TLDR; Commit them to share them with your team..ruleset files are collections of rules and their status (enabled, disabled, severity). When you bind your solution to SonarQube two things happen:a. analyzers are installed to your projects as nuget packages (this is how .net analyzers work btw, you install them just like a reference). There is no other way to install analyzers and this is why your csproj are dirtied.b. ruleset files are created to match the quality profile from the SQ server (the analyzers usually enable all their rules, but the SonarQube quality profile disables some of them and assigns different severities).If you commit the changes, when your colleagues do agit pullall they have to do is build and the analyzer nuget packages will be installed. So they don't need to have the SonarLint plugin installed.
|
I installed SonarLint and hooked it up to our server in Visual Studio, and when I didgit statusit showed all these net.rulesetfiles. Should I put this extension in the.gitignorefile or add them to the repo?
|
Sonar Lint Ruleset files: Gitignore?
|
Open up preferences (cmd + , on the Mac, ctrl + alt + s on Windows), and go to Editor -> Code Style -> Java. On the tabs and indents spaces you can set the indents to 8.
|
I am getting an checkstyle sonar violation on indendation rule (com.puppycrawl.tools.checkstyle.checks.indentation)'public' have incorrect indentation level 4, expected level should be 8.at this linepublic Response getItem(@PathParam(CODE) final ProgramCode programCode,In Intelliji, Kindly suggest on how to change the indentation level to 8
|
Check Style Indentation violation - 'public' have incorrect indentation level 4, expected level should be 8
|
Not sure how your static analysis tool works but -try writing to your value via a static setter:private synchronized static void setDataSource(DataSource ds) {
dataSource = ds;
}so that you can doif(dataSource == null){
setDataSource(getDataSource());
}
|
I have my code as below. I seepublic MyClass{
private static DataSource dataSource = null;
private static DataSource getDataSource(){
if (dataSource == null) {
try {
dataSource = // something.
} catch (Exception e) {
// some exception.
}
}
return dataSource;
}
public List doSomething(){
// ...
if(dataSource == null){
dataSource = getDataSource();
}
dataSource.getConnection();
// ...
}
}I see following message in sonar anaylsis.Dodgy - Write to static field from instance method
This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.
findbugs:ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD Sep12 Reliability > ArchitectureI see everything is okay in this implementation except that we are changing the static variable in doSomething method. How do we fix this ?
|
Write to static field from instance method
|
You have Sonar looking for source code from src/main/java, so it won't find your js code.
Change it to:sonar.sources=src/mainSonar will automatically make the java analysis from /java, and the javascript analysis from /webapp
|
I'm trying to analyse myJEEproject withSonar 4.2. It's amulti-languageJEEproject withJavaandJS.The plugins I've added to mySonar 4.2are :Java 2.1andJavaScript 1.6.Recently, Sonar added themulti-languageanalysis, following thedoc, I've removed thesonar.languagefromsonar-project.properties. But it still analyse only theJava.I'm usingSonnar Runner 2.3inJenkins 1.555. It analyse the project after every build.Am I missing something ?Edit : sonar-project.properties :# Required metadata
sonar.projectKey=myProjectKey
sonar.projectName=MyProject
sonar.projectVersion=1.0
# Path to the parent source code directory.
# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# Since SonarQube 4.2, this property is optional. If not set, SonarQube starts looking for source code
# from the directory containing the sonar-project.properties file.
sonar.sources=src/main/java
# Encoding of the source code
sonar.sourceEncoding=UTF-8Thanks
|
Sonar 4.2 analysis both Java and JavaScript in same project
|
There is a hack which you can use:Normally sonarLint stores the information in yourIntelliJConfiguration-directoryinconfig/options/sonarlint.xml- you can simply paste following configuration into that file:<application>
<component name="SonarLintGlobalSettings">
<option name="sonarQubeServers">
<list>
<SonarQubeServer>
<option name="hostUrl" value="<your-server-url>" />
<option name="name" value="test" />
<option name="login" value="" />
<password />
<organizationKey />
</SonarQubeServer>
</list>
</option>
</component>
</application>which is the basic configuration for a server without authentication.// EDIT: It seems like this was an intended change by sonarSource to sonarLint -https://groups.google.com/forum/#!topic/sonarlint/xnpQmXN8NEo- is the mailing list discussion about this
|
Is it possible to connect to a remoteSonarQube 5.6.1server using theSonarLint 3.0.0plugin forIntelliJ 2017.1without using authentication by default? Currently the plugin seems to want eitherusername/passwordORtoken
|
SonarLint plugin IntelliJ with no authentication
|
Expanding on my comment:Just because one invocation offile.listFiles()returns non-null does not mean the next one necessarily will do. You cannot in general rely on two invocations of the same method (on the same object, with the same arguments) to return the same value, and any method returning a value of reference type may, in principle, returnnull. On reflection you will recognize that you often depend getting different results for different invocations of the same method.file.listFiles().lengthis therefore always an NPE risk.Even if you expect Sonar to have specific knowledge of theFileclass (which does not necessarily seem reasonable), it is genuinely possible for evaluation of your compound conditional expression to throw an NPE. All that needs to happen is for the referenced file to be removed between evaluation offile.listFiles()and evaluation offile.listFiles().length.You could correct this particular issue like this:File[] files;
if (file == null || (files = file.listFiles()) == null || files.length == 0) { /* ... */ }Of course, as @zapi said, iffileis modifiable and accessible to other threads, then pretty much all bets are off.
|
I don't know why Sonar thinks that in the following line a NullPointer Exception may occur:if (file == null || file.listFiles() == null || file.listFiles().length == 0) {//etc}Do you guys have any idea?
|
Sonar: Possible nullpointer?
|
According to the source code (thanks to grepcode.com) for the Sonar C-sharp plugin, a project qualifies as a test project if its assembly name matches the testProjectPattern, which defaults to "*.Tests". It can also be set in sonar-project.properties, like this:sonar.donet.visualstudio.testProjectPattern=*.UnitTestsNote the spelling error (donet)...(!)
|
I have installed Sonar and configured it to analyze our (.NET) projects (using Sonar-Runner). Everything works great, except the tests (MsTest). I've googled around, spent quite some time just trying, but no success. Each time I run sonar-runner, I see the same line in the output:Gallio won't execute as there are no test projectsI've even created a new solution with 2 projects:TestProject=> The 'main' project, has only 1 classTestProject.UnitTests=> has some simple unit tests on the class in theTestProjectIn my sonar.properties file for the solution I have the following line:sonar.dotnet.visualstudio.testProjectPattern=*.UnitTestsRunning the analysis, everything works fine and I get result, except again: "no test projects found."Actually I've tried many things with this property, but none have been successful.
I also tried with a direct path to the dll, with the property:sonar.dotnet.test.assemblies=D:\\Projects\\TestProject\\TestProject.UnitTests\\bin\\Debug\\TestProject.UnitTests.dlland some other paths (relative, etc), but still: No test projects found.Is there anyone who has some experience with this and can help me out with this problem?PS. When I run Gallio on it self, it works, tests get executed, etc.
Also, the path to Gallio in the Sonar properties is correct.
|
Sonar & Gallio: Gallio won't execute as there are no test projects
|
I cant see the specifier of your sonarqube target, but this looks like either a short living branch or a pull request analysis. Those quality gates are always representing the change to the target branch. hence that, you will see no coverage information, if there is nothing new to cover.Add a dummy class, without tests, and check if this issue still persists. Or if i am wrong with my assumption that this is not a long living branch let me know.As an example from an opensource projectPull request analysis with just readme changes -https://sonarcloud.io/dashboard?id=junit-pioneer_junit-pioneer&pullRequest=224Pull Request analysis with a code change and coverage -https://sonarcloud.io/dashboard?id=junit-pioneer_junit-pioneer&pullRequest=216
|
I have issues seeingdetailsof the code analysis in SonarCloud.What I have working is a .Net Core application with Coverlet. I do see that the results are uploaded and the coverage shows. However, I don't get to see a dashboard, the tab 'code' doesn't show code and Measures doesn't give detailed information either.My Github project is linked and as I can see, the results are uploaded.
I wondered why I can't see the code and detailed coverage. I'm not familiar with .NET code and SonarQube was already installed at other projects, so I wondered if I am forgetting something.
I get to see the results for both PR builds as for the specific branch.So my question is how to see the details. Could it be that it only shows on the master branch once I have merged?This is a .NET Core project. I have the same issue with a .NET Framework application.
|
Code and details of code coverage not showing in SonarCloud for .Net solution
|
As far as I can tell from looking into this, the best answer is to just leave it. The compiler will indeed handle the empty files appropriately.SonarQube is just picking it up as code smell, empty files should probably be removed to keep a project in its least complex state possible. In the example you gave with a company going through that many files it is a complete waste of time.
|
Sonarqube is displaying errors for empty css/scss files in the Angular application. What are the effects of having empty scss files? Do they cause issues with performance, side bugs/errors, future problems, what are the compound negative issues? These are generally leftover when we dong generate componentSonarqube flag: Remove this empty stylesheetArticle below states to ignore it, compiler will take care of it, however more interested in the effects of leaving empty files, if there are any.Empty style (.css/.scss) filesCompany would have to go through 1000+ empty scss files in large application, interested to know if its worth the time.
|
Empty CSS/SCSS files and do Angular problems occur?
|
Thesonarqubetasks simply depends on thetesttask by default, according tothe docs:To meet these needs, the plugins adds a task dependency from sonarqube on test if the java plugin is applied.You can easily remove this task dependency and add your own ones:task unitTest {
doLast {
println "I'm a unit test"
}
}
tasks['sonarqube'].with {
dependsOn.clear()
dependsOn unitTest
}Now, only theunitTesttask (and its dependencies) will be executed whenever you execute thesonarqubetask. Please note, thatdependsOnis just a list of dependency entries. You can modify it in many different ways.
|
I am using Gradle with the sonarqube plugin and triggering it usinggradle sonarqubeHowever, it is calling the built in "test" task which runs all types of tests including the integration tests which do not all pass at the moment. I want to be able to specify that the sonarqube task use something like a "unitTest" task instead of the "test" task which runs everything.Other people on the team run cucumber tests within the IDE which also uses the test task, so currently when I exclude cucumber tests in the main "test" task, they have to comment that excludes out in order for their cucumber tests to be kicked off, which is not ideal.I am including sonarqube using the below syntax:plugins {
id "org.sonarqube" version "2.5"
}How can I make the sonarqube task use another test task?Update:Got it to work with the below code, made subprojects run their unitTests first to generate required test report data and then run sonarqube task.// Removes the dependency on main test task and runs unitTests for test code coverage statistics
tasks['sonarqube'].with {
dependsOn.clear()
subprojects.each { dependsOn("${it.name}:unitTests") }
}dependsOn.clear() clears all dependencies, so if there were multiple, I would probably have to do something liketaskName.enabled=falseand then re-enable it after the task was done unless there is a easier way to do it? I've tried dependsOn.remove("test") but that didn't work.
|
How to specify test task run by Gradle SonarQube plugin
|
Best way to handle this problem is to usetry-with-resource. But if someone want to close the connection manually and show the exception of thetryorcatchblock without hiding, following code snippet is the solution.public void upload(File file) throws IOException {
ChannelSftp c = (ChannelSftp) channel;
BufferedInputStream bis = new BufferedInputStream(file.toInputStream());
SftpException sftpException = null;
try {
String uploadLocation = Files.simplifyPath(this.fileLocation + "/" + file.getName());
c.put(bis, uploadLocation);
} catch (SftpException e) {
sftpException = e;
throw new IllegalTargetException("Error occurred while uploading " + e.getMessage());
} finally {
if (sftpException != null) {
try {
bis.close();
} catch (Throwable t) {
sftpException.addSuppressed(t);
}
} else {
bis.close();
}
}
}
|
In java, it is not recommended to throw exceptions insidefinallysection intry-chatchblock due to hide the propagation of any unhandledthrowablewhich was thrown in thetryorcatchblock. This practice is ablockerlevel violation according to default sonar profile.Sonar Error: Remove this throw statement from this finally block.Please consider the following code snippet.e.g.: close input stream inside the finally block, and handle possible exceptions might be occurred when closing the stream.public void upload(File file) {
ChannelSftp c = (ChannelSftp) channel;
BufferedInputStream bis = new BufferedInputStream(file.toInputStream());
try {
String uploadLocation = Files.simplifyPath(this.fileLocation + "/" + file.getName());
c.put(bis, uploadLocation);
} catch (SftpException e) {
throw new IllegalTargetException("Error occurred while uploading " + e.getMessage());
} finally {
try {
bis.close();
} catch (IOException e) {
throw new UnsupportedOperationException("Exception occurred while closing Input stream " + e.getMessage());
}
}
}It would be grateful if you can show the conventional way of handling these situations.
|
How to handle throw exceptions inside finally block in java
|
In General:You need to pass a user token from an account with analysis permissions in your analysis parameters. Use thesonar.loginproperty to do it.Specifically:I see from your travis log that youarepassing what looks like a user token in the sonar.login property.Howeveryou are passing it tosonar.host.url=http://nemo.sonarqube.org. You need to change this tohttps://sonarqube.com
|
I recently started using Travis CI and sonarqube in an open source project and have run into a problem with sonarqube-scanner.My Travis CI page can be seen here:https://travis-ci.org/uglyoldbob/decompilerMy sonarqube page can be seen here:https://sonarqube.com/overview?id=uglyoldbob_decompilerI'm running sonarqube-scanner on Travis CI it suddenly stopped working with the following error:"ERROR: You're not authorized to execute any SonarQube analysis. Please contact your SonarQube administrator."I am using a token generated on sonarqube and have added it to the environment variables of Travis CI. I generated a new token when I noticed the problem and updated the environment variable with Travis but it did not change anything.What can I do to fix this?
|
Not authorized to execute any sonarqube analysis with sonarqube scanner on Travis CI
|
It's indeed no more possible to set the Quality Gate of a project using a parameter when running an analysis.
It's only possible from the UI/WS, where you can specify which Quality Gate should be used for which project.See the documentation for more information :http://docs.sonarqube.org/display/SONAR/Quality+Gates.
|
Context: In Sonar Qube, there exists a custom Quality Gate which is called sayabcd. This is NOT the default quality gate. And in Jenkins, I had configured this SonarQube Quality Gate for a set of APIs by using the parameter-Dsonar.QualityGate=abcdand it was working fine.Recently Sonar Qube was upgraded to version 5.3. Since then, theabcdquality gate is not working and the default quality gate is coming into play instead of theabcdquality gate for all the APIs.On analysis, I came to know thatsonar.QualityGateis deprecated in Version 5.3.Question: Can you please let me know what is the alternative? And how do I make sure that these set of APIs haveabcdas the quality gate and not the default quality gate?I would prefer a solution such that I can configure something on Jenkins as I have access to Jenkins but not to Sonar Qube configurations.
|
sonar.Qualitygate is Deprecated in Sonar Qube 5.3. What is the alternative?
|
In your stylelint config (in this example .stylelintrc.json) add the following rule:{
"rules": {
"selector-pseudo-element-no-unknown": [true, { "ignorePseudoElements": ["ng-deep"] }]
}
}This will allowng-deeppseudo element without disabling the rule
|
I am trying to overwrite the angular material so I used ::ng-deep but is getting error in sonarqube.
please help me to resolve the issue.
|
Unexpected unknown pseudo-element selector "::ng-deep"
|
That totally depends on what you require:Community Edition:It comes with the every-day feature that you require like QualityGate
(custom rule to fail or pass a particular check-in), code smells(best
practice violation), project rating (manageability check),
vulnerability scan, Reliability scan etc. essential feature.Community Edition: see hereDev, EE and DC Edition:They provide you with the git hook to integrate with your project but most of the CI features, branch analysis etc. are restricted to paid versions. Better IDE integration for early detection. And the more you pay for EE and DC edition you get better project management options.That totally depends on how you would like to go forward team size,
the complexity of the project, release cycles, interoperability etc.Other Paid Editions: see hereFeel free to research further before purchasing.My Suggestion:First setup the Community edition either on a VM/Machine or Docker, play with it and then decide whether you require
extra features.
|
I want to implement sonarqube as a code coverage tool, but I am not sure whether I want to use enterprise or community edition, what is the different between them?
|
SonarQube : Enterprise vs Community
|
The translation from hours into days is customisable. By default it's 8 hours, but you can find out your setting by going to Administration > Configuration > Technical Debt.Screenshot of an example, from my project, below:
|
If SonarQube says I have 1 day of technical debt in a project, does that translate to 24 hours of technical debt or 8 hours of technical debt?
|
SonarQube: How many hours in a day of technical debt?
|
Thanks to a similar situation and response at:https://stackoverflow.com/a/37460784/2546381It turned out to be that, the configured docker image, which Gitlab-runner is spinning up, has no Java installed in it and this script requires Java. It is also evident if we look into the sonar-scanner executable (which is a plain text shell script file).
|
While running a test build using Gitlab-CI + Sonarqube, it fails to execute the commandbin/sonar-scanner. I get the error103: exec:: Permission denied.It executes normally on the shell but not via the build automation using the CI.
|
bin//sonar-scanner: 103: exec: : Permission denied
|
You are right, this code is short-circuiting. It's compiled into bytecode roughly like this (assuming Java has goto):if(TheEnum.A.equals(myEnum)) goto ok;
if(!TheEnum.B.equals(myEnum)) goto end;
ok:
// body of if statement
end:So as JaCoCo analyzes the bytecode, from its point of view you have the two independent checks: firstifand secondif, which generate four possible branches. You may consider this as a JaCoCo bug, but I guess it's not very easy to fix this robustly and it is not very disturbing, so you can live with it.
|
This is probably a rather simple question, but I'm at a loss...I have an if statement like the following:if(TheEnum.A.equals(myEnum) || TheEnum.B.equals(myEnum))TheEnumcan beA,B,C, ...G(more than just 4 options).JaCoCo (SONAR) tells me that there are four conditions I can cover here.
Which ones are those?
Isn't the entire set I can test for in this instance essentiallyif(true || not_evaluated) => true
if(false || true) => true
if(false || false) => falseI'm pretty sure I can't specifically test forif(true || true)orif(true || false),
as short circuit evaluation won't get that far...?If so, what is the forth option JaCoCo/Sonar wants me to test for?
|
Test coverage for if statement with logical or (||) - with Java's short circuiting, what's the forth condition JaCoCo wants me to cover?
|
Unfortunately, it is not possible.TheInsufficientBranchCoveragerule applies directly at File level and it is consequently not linked to any particular line in the file. To remove issues related to a given rule key using@SuppressWarnings, the rule has to apply at Class or Method level (as you can read in the documentation).Note that to guarantee consistency of the results of the analysis, we can not disable the issue at File level, as it may end by hiding issues which would have been perfectly legit (take for instance the situation of ajavafile having multiple classes).
|
I need to temporary ignore rule "Insufficient branch coverage by unit tests" (common-java:InsufficientBranchCoverage).Readinghttp://docs.sonarqube.org/display/SONAR/Frequently+Asked+QuestionsI see thatSuppressWarningsshould work for all rules.But any combination of@SuppressWarnings("common-java:InsufficientBranchCoverage")
@SuppressWarnings("InsufficientBranchCoverage")
@SuppressWarnings("java:InsufficientBranchCoverage")does not work for me.I use Sonar 5.0, Sonar Java plugin 3.0.Edit:This warning may be supressed (removed) from sonar UI. I see two solutionsdisable the rule 'Insufficient branch coverage by unit tests' for my quality profile. The drawback is, that rule is disabled for whole project, not just for single classmark issue as ignored when browsing issues drilldown. This ignores only single occurence of the issue. The drawback is, issue need to be marked in every sonar project (we have project-per-branch). When I need to remove warning, I must do this in sonar UI again, for each project.
|
How to SuppressWarnings for 'common-java' rules
|
As far as I can tell, and contrary to someother forum posts, with at least v3.2 of the maven-sonar-plugin (maybe earlier) thesonar.projectKeyproperty is respected and overrides the default of${project.groupId}:${project.artifactId}.Checking the source code also confirms it first looks for the property before defaulting it.org.sonarsource.scanner.maven.bootstrap.MavenSonarRunner.javaprivate static void defineProjectKey(MavenProject pom, Properties props) {
String key;
if (pom.getModel().getProperties().containsKey(ScanProperties.PROJECT_KEY)) {
key = pom.getModel().getProperties().getProperty(ScanProperties.PROJECT_KEY);
} else {
key = getSonarKey(pom);
}
props.setProperty(MODULE_KEY, key);
}
private static String getSonarKey(MavenProject pom) {
return new StringBuilder().append(pom.getGroupId()).append(":").append(pom.getArtifactId()).toString();
}org.sonarsource.scanner.api.ScanPropertiesString PROJECT_KEY = "sonar.projectKey";So by setting the following in the POM, for example, the projectKey can be overriden:<properties>
<sonar.projectKey>myprefix:${project.groupId}:${project.artifactId}</sonar.projectKey>
</properties>Tested on Maven 3.3.9. In case this helps anyone!Link to original GitHub Source:https://github.com/SonarSource/sonar-scanner-maven/blob/master/src/main/java/org/sonarsource/scanner/maven/bootstrap/MavenProjectConverter.java
|
I want to group 25 modules under a single project key so I can get a consolidated view of code duplication. However the sonar maven plugin uses the<groupId>:<artifactId>so each project is separate.I've tried overriding thesonar.projectKeybut the maven plugin doesn't consider it.Is there a way of grouping modules together under a single name so that you can have an aggregate view?
Or is there some other in the sonarqube server to get that aggregate view?
|
Override sonar projectKey when using maven
|
IfRemoteContextis a class you control, and you really don't want to use the usualnew ExceptionType(...)pattern, I would changeRemoteContexttobuildthe exception but notthrowit, and thenif (data == null) {
throw context.buildException("data can't be null");
}...so that it's clear to SonarLint, to the Java compiler, and to programmers doing work on the code later that execution of the method stops at that point (since "raise exception" can mean a lot of things).(Yes, this means changing the lots of places you have this, but a relatively simply search-and-replace achieves that.)
|
So I have an issue with SonarLint that I am not sure how to approach.let's say I have a class with a methodpublic class Class(RemoteContext context)
RemoteContext context = context;
public void String method(String data) {
if(data == null)
context.raiseException("data can't be null");
//do stuff with data like data.get();
}When I analyze this class with sonarLint (3.2.) I get a Null pointer should not be dereferenced issue.So my question is. How to solve this issue?context.RaiseExceptionwill stop method execution so I think it is a false positive.The application has a lot of cases (classes/methods) with this problem.
So I'm thinking that annotations are an overkill (ugly code all around)
I could also type return after eachraiseException()call, but I'm under the impression that is not the "programmers way".I'm guessing writing my own rule would be best.I was looking over the topics and did me googling around but did not find anything useful for this case, when I sort of having to do the "opposite" of what sonar actually does.
Not raising an issue, but kind of "giving a green light" on the method?Hopefully, I was clear enough on the issue.
|
sonarLint complains "Null pointers should not be dereferenced (squid:S2259)" despite that possibility being handled
|
Well, I think for Sonar you could use edu.umd.cs.findbugs.annotations.*, which are deprecated and advise you to use javax.annotation.Nullable.I mainly use the Jetbrains ones,https://www.jetbrains.com/help/idea/nullable-and-notnull-annotations.html, but my main goal is the analysis in IntelliJ.
|
My java method can returnnulland non null results. I want mark method with@Nullableannotation to make it more readable.I usedcom.sun.istack.internal.Nullablebut sonar saysClasses from "sun.*" packages should not be used. Code smell Major squid:S1191.I try to find more similar annotations, but there are variants from different IDE, not from java vendor.Does java (oracle) provides alternatives for nullable annotation or I should use third party libraries only? If I have to use third party library to have an@Nullablewhich one should be good?
|
Java. Which @Nullable should I use to mark return value with one?
|
To solve the issue I contacted Steve Springett, creator of the plugin. He has great end-to-endexamplesof how plugin should be configured.I added<sonar.dependencyCheck.reportPath>${dependency.check.report.dir}/dependency-check-report.xml</sonar.dependencyCheck.reportPath>to the properties of my pom and used following two plugins:<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>1.3.1</version>
<configuration>
<format>XML</format>
<outputDirectory>${dependency.check.report.dir}</outputDirectory>
</configuration>
</plugin>
|
I'm having issues with displaying vulnerabilities on SonarQube. Here are the steps I followed:Installed dependency-check-sonar-plugin version 1.0.3 on SonarQube.Configured dashboard to include Vulnerabilities widjet.Generated dependency report using: mvn org.owasp:dependency-check-maven:1.3.6:check -Dformat=XML.Report was placed into [project]/target/dependency-check-report.xmlRan sonar task: org.codehaus.mojo:sonar-maven-plugin:2.3:sonar
Task completed successfully but I don't see data in the Vulnerabilities widjet.
Anyone has idea what could prevent plugin from seeing report?Thanks in advance!
Rada
|
SonarQube dependency check sonar plugin
|
As documented the Issues Report Plugin is not compatible with versions 5.1 and greater.SonarLint for Command-Lineshould be used to get the same feature. It is simple to enable with Maven:mvn sonar:sonar -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=truePaths to the generated HTML reports are displayed in logs:[INFO] HTML Issues Report generated: /xxx/target/sonar/issues-report/issues-report.html
[INFO] Light HTML Issues Report generated: /xxx/target/sonar/issues-report/issues-report-light.html
[INFO] ANALYSIS SUCCESSFUL
|
I have checked the link:sonarqube issues report,but not clear on how to achive it during maven build.
|
How to generate html report for issues reported using sonarqube-5.4 and maven?
|
This is not a bug, Sonar correctly evaluates that if the listing isexhaustivetheswitch-expressioncan never fall into thedefaultbranch.On the other hand, if you decide to not list all possible enum constants, thedefaultbranch, however, must be declared. Otherwise, the code would not be compilable, because of the requirement that every enum constant can be matched.Note: Your code contains a switch expression, not a switch statement.
|
I have a simple method which takes an enum and returns a String:public static String enumToString(MyEnum type) {
return switch (type) {
case Enum1 -> "String_1";
case Enum2 -> "String_2";
case Enum3 -> "String_3";
case Enum4 -> "String_4";
case Enum5 -> "String_5";
case Enum6 -> "String_6";
default -> null;
};
}But Sonar gives me this Major error:Unused method parameters should be removed.as you can see the parameter type is used in the switch. For more details when I use old switch case every thing is OK.Any idea about the issue, does sonar cover new Java syntaxes?Hmm, I notice that when I removedefault -> null;sonar pass correctly! this is weird.public static String enumToString(MyEnum type) {
return switch (type) {
case Enum1 -> "String_1";
case Enum2 -> "String_2";
case Enum3 -> "String_3";
case Enum4 -> "String_4";
case Enum5 -> "String_5";
case Enum6 -> "String_6";
//default -> null;
};
}
|
Java-17 - switch case - Unused method parameters should be removed
|
I have found out that this issue is due to addition of plugin from root build.grade.To learn more about the gradle plugins you can read:https://docs.gradle.org/current/userguide/plugins.html#sec:old_plugin_applicationAlso, to learn about adding sonarqube to multi-module projects:https://docs.sonarqube.org/latest/analysis/scan/sonarscanner-for-gradle/You have to make the addition of the plugin in your root build.gradle as follows;plugins {
id "org.sonarqube" version "2.8"
}
subprojects {
apply plugin: 'org.sonarqube'
sonarqube {
androidVariant "clienttestDebug"
}
}Hope this helps.
|
Currently we are having problems running sonarqube for just a specific build variant. for exampleclienttestDebugOur structure is like this. We have 3 different build typesReleaseDebugProfileAnd has many (over 30) product flavors. For instanceproductFlavors {
dev {
}
demo {
}
clienttest {
}
...
}So we don't want to run the sonar to run for all variants. Normally there is a way documented as belowsonarqube {
androidVariant 'clienttestDebug'
}However the piece above doesn't work as expected and tries to run for all the variants. Is there something thats missing. We're using sonarqube plugin version 2.7
|
Sonarqube run for specific product flavor and build type (gradle plugin)
|
Looks like you are using defaultbridgenetwork model. Internal IPs are meant for each container to talk to each other underbridgenetworking. You cannot access them from host.There are multiple options for you.You can configurehttp://172.17.0.3:9000as your sonar endpoint in Jenkins.You can configurehttp://172.17.0.2:8000as your jenkins endpoint in sonar.If you don't want to hard code above Ips then both of your containers can talk to each using Docker Default GatewayIp(172.17.0.1) and theirinternalport. so essentially you can configurehttp://172.17.0.1as well.Note - Default Gateway Ip change change if you defineuser defined bridge network.https://docs.docker.com/v17.09/engine/userguide/networking/#the-default-bridge-networkhttps://docs.docker.com/network/network-tutorial-standalone/If you want to spin up both containers using docker-compose, then you can link both containers using service name. Just followNetworking in Compose.
|
I have 2 docker containers running on my Mac host - container 1 isJenkins from Docker Huband container 2 isSonarQube from Docker Hub. I have both containers running successfully. I can access Jenkins from my host by going tohttp://localhost:8080/and I can access my SonarQube by going tohttp://localhost:9000/.The Jenkins container was started like this:docker run -d -p 8080:8080 -p 50000:50000 jenkins/jenkins:latestThe SonarQube container was started like this:docker run -d -p 9000:9000 sonarqubeNow I want to have each container communicate with each other so I need to provide the IP address of the other container to each container.I got theIP address of each containerby executing this:docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_idThis returns an IP address of172.17.0.2for the Jenkins container and172.17.0.3for the SonarQube container. But when I try and access the Jenkins container from my host by going tohttp://172.17.0.2:8080I get a request timeout. The same thing happens when I try and access the SonarQube container from my host by going tohttp://172.17.0.3:9000Is this normal behavior?Shouldn't I be able to access each container from my host by their internal IP address?And how can I test that one container (e.g. Jenkins) can access the other container (e.g. SonarQube) by IP address?
|
How to access Docker container's internal IP address from host?
|
I tested this quite a lot and finally found that setting common rules (anything that starts with "common-xxxx") from scanner side (pom, command line etc) will be ignored and wont work. The language specific rules can be passed as command line arguments and thats why the "squid:S2698" rule is getting ignored correctly. Here is the issue link on the SonarQube JIRA board and it says that it "wont be fixed".https://jira.sonarsource.com/browse/SONAR-8230The only option for you is to set the issue exclusion from UI. Here are the steps to set it from U.If this is a common rule that you want to ignore, then make sure you have admin rights to your project. On the project Dashboard you should see the administration tab:Click on Administration → General SettingsClick on Analysis Scope on the left hand sideNow set the below property:Save and run the scan again.
|
I'm working on the project, where the developers are trying to write understandable code, so there is no sense to use comments in a lot of places. We have a SonarQube, which is used in other projects and we cannot configure it. All we can do is configuring Sonar in our project's POM file. SonarQube is complaining, that there are not comments in our code with the rule"common-java:InsufficientCommentDensity". I know, that we can ignore some rules using sonar.issue.ignore.multicriteria properties like<sonar.issue.ignore.multicriteria>junit.assertions.include.messages</sonar.issue.ignore.multicriteria>
<sonar.issue.ignore.multicriteria.junit.assertions.include.messages.ruleKey>squid:S2698</sonar.issue.ignore.multicriteria.junit.assertions.include.messages.ruleKey>
<sonar.issue.ignore.multicriteria.junit.assertions.include.messages.resourceKey>**/*.java</sonar.issue.ignore.multicriteria.junit.assertions.include.messages.resourceKey>but it's not working with "common-java:InsufficientCommentDensity" rule.Why? And is there a way to ignore this rule in our case?SonarQube version is 6.7 (build 33306)Sonar Maven Plugin version is 3.4.0.905
|
Is there a way to ignore Sonar issue "common-java:InsufficientCommentDensity" for whole project?
|
Sonar says:Using classes and methods that rely on the default system encoding can
result in code that works fine in its "home" environment. But that
code may break for customers who use different encodings in ways that
are extremely difficult to diagnose and nearly, if not completely,
impossible to reproduce when it's time to fix them.you should use theString(byte bytes[], Charset charset)constructor insteadyou can read more about it here:https://gazelle.ihe.net/sonar/coding_rules#rule_key=squid%3AS1943
|
I have got a recurring sonar issue to "Remove this use of constructor "String(byte[])".
One of the example is of the code below:byte[] d = c.doFinal(e);
return new String(d);I do not know why this is popping up. Any help is welcome. Thanks.
|
sonar issue: remove use of String(byte[])
|
This is not a bug, but rather a configuration issue. Rulesquid:S110can be configured to filter out classes from the inheritance tree. By default, no class is ignored and the rule simply count the number of inheritance levels till reachingObjectclass. In order to configure filtered classes, you have to set up thefilteredClassesrule property.Note that it is plan to update to rule to not simply exclude filtered classes from the total inheritance depth, but stop incrementing inheritance levels as soon as reaching a filtered class. The fix will be done when handling Jira ticketSONARJAVA-2252.
|
This is my setup:SonarQube 5.6.6SonarJava plugin 4.8.0.9441Code:public class BaseActivity extends android.app.Activity {}
public class FooActivity extends BaseActivity {}SonarQube thinks thatFooActivityviolatessquid:MaximumInheritanceDepth:This class has 6 parents which is greater than 5 authorized.android.app.Activityis Android Native API.
Shouldn't any super classes ofActivitybe ignored when calculating violations for this rule?Is this a bug?
|
squid:MaximumInheritanceDepth on Android
|
From Sonar's documentation:It is a mix of Line coverage and Condition coverage. Its goal is to
provide an even more accurate answer to the following question: How
much of the source code has been covered by the unit tests?Coverage = (CT + CF + LC)/(2*B + EL)
where
CT = conditions that have been evaluated to 'true' at least once
CF = conditions that have been evaluated to 'false' at least once
LC = covered lines = lines_to_cover - uncovered_lines
B = total number of conditions
EL = total number of executable lines (lines_to_cover)Source:https://docs.sonarqube.org/display/SONAR/Metric+Definitions#MetricDefinitions-Tests
|
Sonar gives a value of Overall coverage which is a combination of line and branch coverage. I am not sure how important is this metric. What does the value of overall coverage signifies? How it is better than line and branch coverage? Any suggestions would be helpful.
|
Sonar-Overall Coverage
|
Seems it's an issue with the SonarQube VSTS Extensions:The SonarQube extension uses basic authentication to communicate with
the SonarQube API endpoint, and uses the token as username, and
password as null. The npm package 'request' (at least latest version
2.83.0), does not allow null passwords and returns 'auth() received invalid user or password'.To fix it, the password should be set to an empty string instead.Until the VSTS plugin is fixed by SonarSource, you can workaround the
issue by manually editing the extension on your VSTS build machine.
The file to edit is:<build
location>\_tasks\SonarQubePublish_291ed61f-1ee4-45d3-b1b0-bf822d9095ef\4.0.0\common\helpers\request.jsAdd a new row after row 22:options.auth.pass = "";Just refer to this similar thread for details :Unable to integrate SonarQube analysis results with VSTS Build Summary
|
On TFS, I am not being able to run the taks "Publish Analysis Result" to publish Quality Gate on TFS web page. The other tasks "Prepare analysis on SonarQube" and "Run Code Analysis" runs successfully.The error messages are:[error][SQ] Could not fetch metrics[error][SQ] Could not fetch task for ID 'FWK9NiOFibiMfA2L0BHo'Despite the error message, when I access the urlhttp://localhost:9000/api/ce/task?id=FWK9NiOFibiMfA2L0BHoI get a json response with the task information.
|
Sonarqube v.4 TFS task "Publish Analysis Result" throw error "Could not fetch metrics"
|
I found an answer in the sample sonar project:https://github.com/SonarSource/sonar-examples/tree/master/projects/languages/java/code-coverage/ut/ut-maven-jacoco.Jacoco listener has to be configured for surefire plugin.<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<!-- Minimal supported version is 2.4 -->
<version>2.13</version>
<configuration>
<properties>
<property>
<name>listener</name>
<value>org.sonar.java.jacoco.JUnitListener</value>
</property>
</properties>
</configuration>
</plugin>and dependency added:<dependency>
<groupId>org.sonarsource.java</groupId>
<artifactId>sonar-jacoco-listeners</artifactId>
<version>3.8</version>
<scope>test</scope>
</dependency>Also some combination of the following parameters for sonar plugin was needed:sonar.java.surefire.reportspath
sonar.junit.reportsPath
sonar.tests=src/testThe last one sealed the deal
|
We have a CI setup in Bamboo which runs Junit Tests and computes Unit Test Coverage using Jacoco. Then we run Sonar plugin for source code analysis. Everything is working great and we can see the analysis on the SonarCube server, inlcuding coverage, but we would like to see exactly which tests cover certain line of code. Right now it just says:covered by unit tests.Is there a way to do that?
|
Sonarqube: view unit tests that cover the source
|
You cannot use an existing.DotSettingsfile with SonarQube's R# plugin at the moment.This feature however will be added in the upcoming release of the R# plugin, refer tohttp://jira.sonarsource.com/browse/SONARRSHPR-15for details.Note: The re-use reports mode was already supported in the past (with the C# plugin version 2.x), but has since been removed (since 3.x).
|
I have a C# Project with a ReSharper Dotsettings file. I want to configure Sonar so that it uses my Dotsettings file. In my Dottsettings file i disabled many Rules. How can I integrate this file in SonarQube?This is my sonar-project.properties file (just the ReShaper part):#ReSharper
sonar.resharper.mode=
sonar.resharper.dotSettings.path=MyProject/ReSharper7-Coding-Style.dotsettingsI also have the same problem with StyleCop.
This is my sonar-project.properties file (just the StyleCop part):# StyleCop
sonar.stylecop.mode=
sonar.stylecop.projectFilePath=MyProject/Settings.StyleCopfyi: I run the SonarQube analysis with Bamboo.
|
How can I integrate ReSharper's Dotsettings File in SonarQube?
|
Given your tool chain, the only thing that's different compared to Java/JUnit is to make Groovy (test) compilation work in Maven (see thespock-exampleproject). Other than that, you shouldn't have to do anything special, as Spock is just a custom JUnit runner that's activated automatically. You'll get the same reports etc. You can even have Spock and JUnit tests in the same source directory and run them together.
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed2 years ago.Improve this questionWe decided to give Spock a try as a testing framework for our java based EE application. Currently we have a CI infrastructure deployed based on jenkins + maven + jacoco.Q:the question is what's the best way to integrated spock with all this? Any recommendations, best practices?
|
Best practice integrating Spock with Jenkins, Sonar [closed]
|
It turned out that it works if I use an absolute path for the xml report file. So I added<sonar.coverage.jacoco.xmlReportPaths>${project.basedir}/../coverage/target/site/jacoco-aggregate-all/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>to the top maven pom soeach modulepoints to the same report file. For a deeper nesting of module directories you have to introduce a propertymain.basediror something.The main understanding is that you do not provide sonar a coverage report which get mapped to the module classes, but you provide module classes which get mapped to a coverage report.
|
I have a multimodule Maven project where the coverage reports are located in another module than the covered Java classes. An import of a not empty xml coverage report (with coverage information) into Sonarqube is successful but shows a coverage of 0.Steps to reproduce:Checkout followinggithub projectand build it withmvn clean verify. After that there exist an aggregated xml report located incoverage/target/site/jacoco-aggregate-all/jacoco.xml. You can see coverage data in there and also in the corresponding html-Report.Start sonarqube (current version 8.4.1) with following command and wait a little bit.docker run -d -p 9000:9000 sonarqubeedit: Plugin "JaCoco xml report importer" is already installed in this image.Publish coverage data with following (verbose) command. Importing of report was successful (see log).mvn sonar:sonar -X -Dsonar.projectKey=example -Dsonar.host.url=http://localhost:9000 -Dsonar.login=admin -Dsonar.password=admin -Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco-aggregate-all/jacoco.xml
## Log output contains
...
10:54:28.519 Reading report '<project-path>\maven-multimodule-coverage\coverage\target\site\jacoco-aggregate-all\jacoco.xml'
...Browse tohttp://localhost:9000/dashboard?id=example. You see coverage of 0.What am I doing wrong?
|
Sonarqube: Import Jacoco xml report for multimodule
|
You're right and I've created the following Jira tickethttps://jira.sonarsource.com/browse/SONARJAVA-1924. Thanks for your feedback !
|
I think I have found a false positive while using the@Getterannotation fromProject Lombok.In the following example class I got the warning"Private fields only used as local variables in methods should become local variables"(squid:S1450).public class Example {
@Getter
private String exampleField; // <-- squid:S1450
public Example(final String value) {
setExampleField(value);
}
private void setExampleField(final String exampleField) {
this.exampleField = exampleField;
}
}Can someone confirm this? Is it a bug in the SonarQube rule or is there something wrong with my class or with my understanding of this rule or the@Getterannotation?Just for the sake of completeness:Project lombok annotations or the generated methods are recognized correctly in other SonarQube rules. So I think my setup is fine.I have also tried to put the@Getterannotation on class level and I got the same warning.The warning is shown in SonarLint (in IntelliJ IDEA) and in the web interface of SonarQube. So I think it's not an error while executing the analyzer.I have bound the SonarLint pluign in IntelliJ IDEA to our SonarQube Server and this remote connection works.I have tested with the following versions:SonarQube 6.0SonarQube Java Plugin 4.2SonarLint (for IntelliJ IDEA) 2.3.2IntelliJ IDEA 2016.2.5Java 8
|
SonarQube false positive squid:S1450 for @Getter (lombok) annotated fields
|
We have already changed the default Regex for this rule to allow underscores. The next version of the C# plugin will use that. Until then you can change the Regex yourself to^[A-Z][a-zA-Z0-9_]*[a-zA-Z0-9]$.
|
The Sonar rule csharpsquid:S100 (Method name should comply with a naming convention) is thrown also for event handlers that are generated by Visual Studio, something like:protected void Page_Load(object sender, EventArgs e)
{
DoIt();
}Is it possible to ignore this rule for event handlers as they are auto-generated?
|
Method names for event handlers S100
|
It's better to migrate to JAX-RS 2.0 client classes. Some refactoring would be necessary though. See themigration guide. For example, if you wrote like this before:Client client = Client.create();
WebResource webResource = client.resource(restURL).path("myresource/{param}");
String result = webResource.pathParam("param", "value").get(String.class);You should write now like this:Client client = ClientFactory.newClient();
WebTarget target = client.target(restURL).path("myresource/{param}");
String result = target.pathParam("param", "value").get(String.class);
|
I am usingjersey clientfor rest calls. Imports for my code are:import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;Everything is working fine. I am usingSonarfor checking my Code quality.sonar is showing a major issue for:Classes from "com.sun." and "sun." packages should not be usedIs this actually bad practice to use classes from sun?If yes, what are the alternatives?
|
Classes from "com.sun.*" and "sun.*" packages should not be used Sonar issue for Jersey client
|
We need to implement special processing when an Android project is detected. Correctly setting sonar.java.libraries is one of the requirements. A ticket already exists, feel free to vote or provide a pull request.https://jira.sonarsource.com/browse/SONARGRADL-6Update: we have released version 2.1 of the plugin (currently RC2) that natively supports Android projects. Propertiessonar.java.[test.]binariesandsonar.java.[test.]librarieswill be automatically populated.
|
What I want to achieve:In sonar it is possible to track third party dependencies used throughout Projects by setting the property "sonar.libraries" and perhaps there are more benefits (such as detecting which violations are caused by external libraries?)What I tried to do:I set the value tobuild/intermediates/pre-dexed/debug/*.jarbut this seems to have little effect.Question:Since it is no longer needed to use the "libs" folder for third party dependencies, what is the recommendation for the property called "sonar.libraries"?
|
Proper configuration for "sonar.libraries" in a modern Gradle Android project
|
In your if condition block, you are settingvariableto null and it happens to be your method parameter. Instead of assigning the value to the method parameter, create a local variable and use it and return the value of the local variable from the method if at all it is intended.
|
I'm programming a Controller using Java and I'm checking the style using Sonar. In my Sonar I have an error that says:'Assignment of Parameter 'variable' is not allowed.The line that it's on is:@RequestParam(value="variable", required=false) String variableSo I'm wondering how I could get that error off since I can't just create a setter when I'm using that annotation.EDITI'm usingEclipse. The rule being broke isParameter Assignment.@RequestParam(value="variable", required=false) String variable
if (variable != null && variable.compareTo("") == 0) {
variable = null;
}
|
How to remove 'Assignment of Parameter 'variable' is not allowed'
|
This indeed is a known limitation of the plugin, which depends on this ticket:https://jira.sonarsource.com/browse/SONARCS-657For your information, the main difficulty to implement this feature is due to unit test reports not containing links back to the source code files, but only to assemblies/types/methods instead. SonarQube needs to know which files to show in the drilldown.
|
We use Jenkins to build C# project, to run unit tests (NUnit) and code coverage (NCover). As output,coverage.nccovandnunit-result.xmlfiles.Jenkins triggers SonarQube analysis (SonarQube 5.0.1 and up to date C# plugin). The SonarQube dashboard displays unit tests coverage and unit tests results, but list of failed tests cannot be displayed as drilldown.When user clicks on the metrics, the page displayed is quite empty (no list of files, no drilldown, just the metric).sonar-project.properties:sonar.visualstudio.solution=MyProject.sln
sonar.cs.ncover3.reportsPaths=coverage.nccov
sonar.cs.nunit.reportsPaths=nunit-result.xmlUnit Tests Coverage metrics display drilldown as expected.
|
No drilldown from SonarQube Unit Test Success widget
|
I would also backup the configuration files ($SONARQUBE_HOME/conf), plus the list of plugins ($SONARQUBE_HOME/extensions/plugins).
|
Today I am backing up MySQL with mysqldump, but I am not sure if I need to save some files from /opt/sonar. Please could you help me with some instructions?
What do I need to backup in Sonar in addition of MySQL?
|
How to backup SonarQube server?
|
I had this problem by myself while developing a plugin.
I think you were using the sonar--plugin-archetype to create your surrounding. If you do so your whole project is under GNU 3 license and a header within every class is expected telling this. The predefined pom.xml contains a part where this is defined. Search for "license" in your pom.xml and delete this part.If this is not fixing you problem just add-Dlicense.skip=trueto your maven goal.The expected header is like (please notice that the first things are set while you use -sonar-archetype)/*
* MyLanguage Plugin
* Copyright (C) MyYear MyCompany
*[email protected]*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
|
I am creating a new language plugin forsonarqubein Eclipse with maven project and facing following error while building the project:Failed to execute goal com.mycila.maven-license-plugin:maven-license-plugin:1.9.0:
check (enforce-license-headers) on project sonar-java-plugin:
Some files do not have the expected license header -> [Help 1]
|
Sonar plugin error in eclipse maven project
|
The current workaround is to unsetGEM_PATHandGEM_HOMEvariables before launching the sonar webservice:unset GEM_PATH GEM_HOME
./sonar.sh consoleThis doesn't have to be done for the sonar-runner environment.The problem is caused due toconflict with Ruby local installation.
|
I have an instance of sonar running on my local machine at localhost:9000, and I'm able to go to and use the console. When I try to run sonar-runner from the command line for a project, I get a 500 error:Exception in thread "main" org.sonar.runner.RunnerException: org.picocontainer.PicoLifecycleException: PicoLifecycleException: method 'public void org.sonar.batch.bootstrap.DatabaseCompatibility.start()', instance 'org.sonar.batch.bootstrap.DatabaseCompatibility@3848110b, org.sonar.api.utils.HttpDownloader$HttpException: Fail to download [http://localhost:9000/api/server]. Response code: 500
at org.sonar.runner.Runner.delegateExecution(Runner.java:288)
at org.sonar.runner.Runner.execute(Runner.java:151)
at org.sonar.runner.Main.execute(Main.java:84)
at org.sonar.runner.Main.main(Main.java:56)
Caused by: org.picocontainer.PicoLifecycleException: PicoLifecycleException: method 'public void org.sonar.batch.bootstrap.DatabaseCompatibility.start()', instance 'org.sonar.batch.bootstrap.DatabaseCompatibility@3848110b, org.sonar.api.utils.HttpDownloader$HttpException: Fail to download [http://localhost:9000/api/server]. Response code: 500
at org.picocontainer.monitors.NullComponentMonitor.lifecycleInvocationFailed(NullComponentMonitor.java:77)
...
...But when i visit the url in my browser, I get the following xml response:<server>
<id>20131007131041</id>
<version>3.4.1</version>
<status>UP</status>
</server>I'm not sure where to go from here. Any advice?
|
Failure running sonar-runner locally
|
I've solved this using the following approach:All jenkins projects are named after their git repository ( I use gitolite )I have activated onlyTrigger builds remotelyfor the base buildsI have added apost-receivehook in gitolite which does something like$CURL --silent --netrc --insecure --connect-timeout 2 "$GIT_REMOTE_TRIGGER_URL/$GL_REPO/build?token=$JENKINS_BUILD_TOKEN" > /dev/nullScheduled all sonar jobs to poll the SCM every 24 hours
|
I have the following setup active and working:Jenkins with Git and Sonar pluginsOne jenkins job (project) which polls Git each minuteOne jenkins job (project-sonar) which polls git each 24 hoursBoth jobs share the same git repository.This allows me to build my project for each commit and then each day, only if the project has changed, run the Sonar analysis.I've recently set up the git repository to send notifications to Jenkins when a project has changed, as perPush notifications from repository. This builds both projects immediately, but I want only the quick (project) job to build. If I move theproject-sonarto be built periodically, the sonar analysis will be run even if there are no code changes, which is wasteful.How can I retainimmediate build for theprojectbuilddaily build for forproject-sonarbuild?
|
Build project periodically only if changes are found in the repository
|
If you have Resharper in Visual Studio you can use thecognitivecomplexityresharper plugin.It shows the cognitive complexity even though it is below the (in Resharper options configurable) threshold
|
While using SonarLint and SonarQube in Visual Studio (2017), is there a way to display the Cognitive Complexity of a method anywhere?It is shown when it exceeds the maximum value, but I can't seem to find where I can see it once I'm below the threshold.
|
Show Cognitive Complexity of method in Visual Studio
|
Note: Make sure you runterminal as administratoror withsudo1. Run command to fetch certificate your sonarqube$ openssl s_client -showcerts -connect {domain}:{port}
example:
$ openssl s_client -showcerts -connect sonarqube.com:4432. Copy certificate to a new filemycert.pemNew file: mycert.pem3. Import the certificate to JDK->JRE$ keytool -importcert -file {filename}.pem -keystore "{jdk_path}/jre/lib/security/cacerts" -alias "{somename}" -storepass changeit
example:
$ keytool -importcert -file mycert.pem -keystore "/c/Program Files/Java/jdk1.8.0_202/jre/lib/security/cacerts" -alias "MyCert" -storepass changeitType yes4. Run SonarQube Command with your sonarqube link$ mvn clean package -U sonar:sonar -Dsonar.host.url=https://sonarqube.com -Dsonar.projectKey=MyApp -Dsonar.projectName=MyApp -Dsonar.projectVersion=2.4.1 -Dsonar.language=java -Dsonar
.sources=src/main/java -Dsonar.tests=src/test/java '-Dsonar.exclusions=**/*Test*/**' -Dsonar.java.binaries=target/classes -Djavax.net.debug="ssl,handshake"
|
I try to launchmaven sonar:sonarto a SonarQube instance on HTTPS connection with a self-signed certificate. Maven give me this error:[ERROR] Failed to execute goal
org.sonarsource.scanner.maven:sonar-maven-plugin:3.4.0.905:sonar
(default-cli) on project data.model: Unable to execute SonarQube: Fail
to get bootstrap index from server:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target -> [Help 1]
|
Maven sonar plugin: trust self-signed certificate
|
The URL to static images are hardcoded to the old GitHub source repository (SonarCommunity/sonar-github). GitHub used to provide a redirection, but it is no more working.There's a ticket to fix this (SONARGITUB-32) and we're going to make a release soon.
|
Lately our SonarQube PR analyses have been with broken images, as it seems that the requests tohttps://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.pnggenerate404: Not Found.And our PRs look like this:I could not open up ticket as it seems SonarQube community requires that the issues are to be discussed in StackOverflow. Anyone else having similar issues?
|
SonarQube icons are not showing correctly
|
It is probably because the binary files are not provided correctly. I had a similar issue with my SonarQube configuration, then I discovered that the classes that implementSerializableare in different modules and/or in an external library.Setting correct values forsonar.java.binariesandsonar.java.librariesallow SonarQube to locate the binaries and correctly determine whether or not the classes are serializable.
|
SonarQube 5.1 marks a lot of critical issues after reviewing my code. However the class itself and the referenced class in the field is also serializable. The referenced class inherits the serializable interface through a class.Here is my examplepublic class A implements Serializable {
private B b; // -> Sonarcube markes this field as not serialzable
}And the class B is defined as followspublic class B extends C {
....
}And the class C is defined as followspublic abstract class C extends D {
....
}And the class D is definedpublic abstract class D implements Serializable {
....
}Running FindBugs on the same project does not see these problems.
I am not sure if it is a bug in sonarcube or is my code has some other problems (other fields in the classes C,D or something else)Does anybody has a clue ?
|
Make "class" transient or serializable BUT the class is serializable
|
Ok the solution was quite obvious. SonarCube 4.1.1 does not come with Cobertura preinstalled, so I installed it and now it works :) Maybe it was preinstalled in 3.2 version, I can't remember.
|
I am analysing a Java project that has been unit tested and Cobertura coverage.xml reported. I am using SonarQube 4.1.1 and latest Sonar Runner. I have successfully imported Cobertura coverage results to Sonar 3.2 and Ant analyzer, but with this new version I am running into problems. In the new Sonar analysis execution (through Jenkins) I see no reference in logs that it would have started any Cobertura engine or anything. My settings in Runner Jenkins project:sonar.dynamicAnalysis=reuseReports
sonar.java.coveragePlugin=cobertura
sonar.cobertura.reportPath=[mypath]/coverage.xml
sonar.junit.reportsPath=[mypath]/No mentioning of Cobertura in the analysis output (except my own property values) and SonarQube page shows "-" in coverage report. Unit test results are shown fine.I have also added all source, bin, and test directories. Any ideas? Thanks.UpdateI wonder if the reason why Cobertura coverage is not reported on SonarQube page, is because in Jenkins my SonarQube project clones (Clone plugin) the workspace from a previous Project build? If the coverage.xml file contains static paths, then maybe it goes wrong somehow.
|
SonarQube not picking up Cobertura code coverage
|
If you are running OpenCover from the sonar gallio plugin (from thesonar C# ecosystem), a simple solution to get alerts on low code coverage could be the sonarbuild breaker plugin.
You would get a broken build when coverage get below an alert threshold. This solution does not allow to get graph or trends in jenkins, but again if you use sonar, you have everything in the sonar dashboards.
Hope it helps
|
I'm working on a .NET project that usesJenkinsas the CI server. The server is working as it's supposed to but now I'm trying to make it emit alerts in case oflow code coverage.The approach that I'm trying is to useSonarto executeNUnitandOpenCover, but I need to link thecode coveragemetrics fromSonarback toJenkinsand that's where the problem resides.AFAIK the report generated fromOpenCover(coverage-report.xml) as is, is not recognized fromJenkinsso what I'm trying to do is to make them talk by a xsl file that transforms the (coverage-report.xml) to a (emma-report.xml) thatJenkinshas plugins that understands.Although I don't know it that is the best approach.Better approaches are more than welcome ;)I'm facing a problem to get theblock coveragemetrics from OpenCover (Emmaneeds this metric).I've managed to transform all other metrics neededclass, %,method, %andline, %fromOpenCovertoEmma, but I'm not sure if is possible to get theblock, %from the report.Can anyone tell me if it is possible or if there is a better approach to achieve what I'm trying to do (that is, makeJenkinsemit build alerts when code coverage is bellow a certain percentage)?Thanks in advance! :)
|
Is there a way to retrieve code coverage metrics generated from OpenCover back to Jenkins?
|
+100You could follow the guide "Create a plugin with custom rules", using the template projectplsql-custom-rules.That is more complex thanadding a rule to XPATH, but you would have more control.To create a check, you can create a subclass oforg.sonar.plsqlopen.checks.AbstractBaseCheck.You can use theorg.sonar.check.Ruleandorg.sonar.squidbridge.annotations.SqaleConstantRemediationannotations to configure the check metadata (name, description, key...).Very often you'll need to override just two methods:init(): subscribe to the desired grammar rulesvisitNode(AstNode): analyze the nodes that match the subscribed grammar rulesBut first, as illustrated inissue 21, do check that your code does not error with an "Unable to parse file" message.I just need to know a parser like sonarqube analysis to detect compilation errors in the script fileCheck that your case is not an optional semicolon one, as in "Semicolon is not required inCREATE VIEW".Looking at that source code is a good way to check how the parser like sonarqube analysis detects compilation errors in the script file.
|
I am using Jenkins and SONARQUBE PL/SQL plugin for Oracle SQL code analysis,
I need to create Custom rules usingXPATHfor Quality Analysis of the SQL Script files that are sent for deployment over Jenkins.I am trying to create a custom rule that detects if a semicolon (" ; ") is missing at the end of any SQL commands.
SQL termination ("semicolon") is of importance for deploying SQL scripts with SQLPLUS.example of codeinsert into table_name values('wait','for','completion'); -- compliant with script
insert into table_name values('somename','for','good'); -- compliant with script
**insert into table_name values('someplace','for','game')** -- non compliant as semicolon missing
insert into table_name values('something','for','change'); -- compliant with script
delete from table_name ; -- compliant with script
delete from table_name ; -- compliant with script
update table_name set name='james' where id='22';there is a insert query that ismissing the semicolon, and hence sonarqube should detect this and fail the jenkins build or fail the SONAR Quality test.please help creating the PLSQL custom rule for detecting correct SQL termination by semicolon.example of xpath would be:/COMPILATION_UNIT/ANY_DML_EXPRESSION/following-sibling::SEMICOLON -- something like this
|
Sonarqube PLSQL Custom rule for detecting correct SQL terminator semicolon within a SQL script file
|
My answer could seem quite direct and valueless, but it is more for getting things together and to summarise.First thing, it that there is no "golden bullet" solution of this problem. Something definitely has to be changed and I see 3 options or 3 alternatives:RemoveSerializableinterface. It is not a "good practice" to putSerializableon all entities. It is needed only if you are going to use instances of it as detached objects:When and why JPA entities should implement Serializable interface?.Use Timestamp type instead of LocalDateTime. It seems to me that it is equivalent:https://github.com/javaee/jpa-spec/issues/63Instant, LocalDateTime, OffsetDateTime, and ZonedDateTime map as
timestamp values by default. You may mark a property of one of these
types with @TeMPOraL to specify a different strategy for persisting
that property.If both first options do not work for you, then (I am pretty sure, you know what to do) - suppress this warning@SuppressWarnings("squid:S3437").
|
Classes asLocalDateTimefrom the packagejava.timearevalue based classes. If I have an entity using such an object as a field I run into the following "problem":
Value based classes shouldn't be serialized. However, the JPA entity has to implement the interface Serializable. What is the solution for that paradox? Shouldn't someone use LocalDateTime as a field of an JPA entity? Use Date instead? This would be unsatisfying.This problem is a Sonar rulesquid:S3437and therefore there are a lot of bugs in the project, since we changed from Date to LocalDateTime ...Non compliant solution due to value based class usage:@Entity
public class MyEntity implements Serializable{
@Column
private String id; // This is fine
@Column
private LocalDateTime updated; // This is not ok, as LocalDateTime is a value based class
@Column
private Date created; // This however is fine..
}
|
java.time and JPA
|
While SonarQube is used to run the analysis of your entire project,SonarLintcan be used to get a rapid feedback on your current development. SonarLint provides a SonarQube analyses in you favorite IDE for Java, Javascript, PHP or .Net.Note thatSonarLint for CLIalso make you able to get in command line the difference between what is currently on your workspace and what has been analyzed during last SonarQube analysis.Finally, some SonarQube plugins have been created to analyze pull requests for some SCM based on git:
*SonarQube Github plugin*SonarQube Gitbucket plugin*SonarQube GitBucket On Demand plugin
|
Using Sonar how to do static code analysis only for current changes which i have done. for example my project 100 class/file and i made change to a class/file, now sonar has to run static code analysis only for that particular not for the entire project. how to achieve it?
|
SONAR static code analysis for current changes only
|
The SonarQube Scanner for MSBuild and the SonarQube C# plugin currently expect all files of the project to have the UTF-8 encoding - and this is hardcoded.There is a ticket to improve this in a future version:https://jira.sonarsource.com/browse/SONARMSBRU-174
|
I have a couple of files that are not analyzed with the following message:Invalid character encountered in file [file name with full path] at
line 9 for encoding UTF-8. Please fix file content or configure the
encoding to be used using property 'sonar.sourceEncoding'.In Visual Studio when I select File / Advance Save Options, the files were set to Western Europe (Windows) - Codepage 1252.I changed it to Unicode (UTF-8 with Signature) - Codepage 65001.But SonarQube still complains about the invalid characters. The "invalid characters" are comments in German with Umlaut-characters (ä,ö,ü)What can I do to fix this (without removing the comments)?
|
Some files not analyzed by Sonar "Invalid character encountered in file"
|
It looks your issue was solved just two days ago.https://jira.sonarsource.com/browse/SONARJAVA-808
|
At first I had a class along the lines of:public class MyClass implements Serializable {
private List<Role> roles;
}SonarQube pointed out thatList, a member of a serializable class, is not serializable itself. Fair enough, I'll switch to a serializable implementation ofListlikeArrayList.public class MyClass implements Serializable {
private ArrayList<Role> roles;
}At this point SonarQube is unhappy because "roles should use an interface such as 'List' rather than an implementation like 'ArrayList'" which brings me back to where I was originally.Is there a way out of this loop?
|
SonarQube catch 22 with serializable lists
|
It is working fine now. Thanks for your Knowledge sharing.
I am able to authenticate and authorize Sonar 3.5.1 using the username from the LDAP groups.
Steps :
Needed to create the group name in SONAR 3.5.1 which is the same group name or DL name in LDAP.e.g CHENNAI-GROUP is the DL name/group name available in LDAP. You should create CHENNAI-GROUP as a group name in Sonar too and map the created group name in Sonar to any project available in Sonar.
So after the next login to Sonar , any username under CHENNAI-GROUP in LDAP will be newly added to the group created in Sonar too and the mapped projects will be accessible to the username
Make sure the LDAP CN names and OU names to be in correct order.
Please add the following lines as below. Do not add anything more than this. Remove anything if you have added already.
Append the following lines in %SONAR_HOME%/conf/sonar.properties**## LDAP configuration
sonar.security.realm: LDAP
#sonar.authenticator.createUsers: true
ldap.url: ldap://******:389
ldap.user.baseDn: OU=<USERS>,OU=<Users>,OU=chennai,DC=<orgDC>,DC=CORP,DC=<org>,DC=IN
ldap.bindDn: <username>@<orgDC>.CORP.<org>.IN
ldap.bindPassword: ******
ldap.user.request: (&(objectClass=User)(sAMAccountName={login}))
ldap.group.baseDn: OU=DL,OU=<GROUPNAME>,DC=<orgDC>,DC=CORP,DC=org,DC=IN
ldap.group.request: (&(objectClass=group)(member={dn}))
ldap.group.idAttribute=cn
################################**#
|
Authentication for Sonar (3.5.1) with LDAP plugin (1.3-SNAPSHOT) is working fine. But the authorization for projects is not working with groups.
From the Admin user i am able to map the LDAP user to a group created in Sonar UI.
But everytime the user tries to login to Sonar, the users already mapped to a group gets deleted from the group.Has anyone faced the same issue already? is that a problem with ldap version? or do i need to make configuration changes?
|
LDAP authenticated user gets deleted from the group created in sonar for every fresh login to sonar
|
The tar is created with the permission of the user running it. If you want this to be a particular user/group you can runmavenas that user/group.Maven may not allow you to use tar as a different user, but if you can do it in ant you can usehttp://maven.apache.org/plugins/maven-antrun-plugin/to do anything ant can do.http://maven.apache.org/plugins/maven-antrun-plugin/usage.html
|
I'm using Maven with the Assembly plugin and would like to set the user and group for a tar-file.I can set access rights to every directory, but without setting the user this is quite useless.Any ideas?
|
Maven assembly set username for tar
|
You can uselintrand upload the results toSonarQube. There is an example at here:https://github.com/paulospx/sonarqube-r
|
A simple question: does anybody knows if a tool similar to sonarqube exists for R code? or a sonarqube library?
I mean, a tool for analyzing technically quality of the code, not only highlighting or sintax formating.
thanks in advance!
|
Analyze and measure technical quality in R code: any tool similar to SonarQube?
|
+50Our styleguide demands a specific header for Java sources :/*
* [optional text] <CreationDate> [optional text]
* <Copyright (c) yyyy FOO-COMPANY. All Rights Reserved.>
*/[] brackets means it's optional, <> means this must be present, f.e. :valid/*
* 03.05.2016
* Copyright (c) 2016 FOO-COMPANY. All Rights Reserved.
*/also valid/*
* just some text 03.05.2016 Fred Fart
* Copyright (c) 2016 FOO-COMPANY. All Rights Reserved.
*/The regex ensures that dates are valid, and also multiple dates are possible, f.e. :/*
* 23.09.2016
* Copyright (c) 2013-2016 FOO-COMPANY. All Rights Reserved.
*/or/*
* 23.09.2016
* Copyright (c) 2013,2014,2016 FOO-COMPANY. All Rights Reserved.
*/The rule has to be configured with your regexp asheaderFormatandisRegularExpression=trueOur regex is configured like that:^.+(?:0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19[7-9]\d|20[0-2]\d).+?Copyright \(c\) ((\b19[7-9]\d|20[0-2]\d)([,|-])?\b)* FOO-COMPANY\. All Rights Reserved\..+
|
SonarQube has a rule that allows you to verify each file is headed by a copyright and/or license. However, I'm not certain how to specify a copyright with a variable year.For example, here is their compliant solution:/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/The params requested are:isRegularExpression
Whether the headerFormat is a regular expression (Default Value: false).headerFormat
Expected copyright and license headerIf the "2008-2013" was instead a single year, how would I provide a format that would allow both 2015 and 2016, for example?
|
SonarQube "Track lack of copyright and license headers" parameters
|
This is a limitation of thePDF Report Pluginthat is developed by Klicap:http://jira.codehaus.org/browse/SONARPLUGINS-1510If you remove this plugin, then everything should be back to normal.
|
I am running maven with sonar. Since I activated authentication on sonar for security purposes, since then I got the following error:[ERROR] Can´t access to Sonar or project doesn't exist on Sonar instance. HTTP KO to http://localhost:9000/api/resources?resource=com.myproject.soft:soft&depth=0&format=xml
java.io.IOException: Can´t access to Sonar or project doesn't exist on Sonar instance.
at org.sonar.report.pdf.util.SonarAccess.getUrlAsDocument(SonarAccess.java:132)
at org.sonar.report.pdf.entity.Project.initializeProject(Project.java:98)according tohttp://docs.sonarqube.org/display/SONAR/Analyzing+with+MavenI should use the following parameters:-Dsonar.login=login -Dsonar.password=passwordThose settings are not working for me.The full command I am using is:mvn install sonar:sonar -Dsonar.login=login -Dsonar.password=password
|
Maven with sonar authentication
|
I got the answer fromjacoco plugin coverage in multi-moduleThe following were the mistakes that I did which caused problem form me. In the properties of our pom<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>and in plugin<destFile>${sonar.jacoco.reportPath}</destFile>for me, the above statement flushed thejacoco.execin different folders because of difference in maven module hierarchy as a result they never agrregated.The second point is that the dependent module coverage will be only obtained only if it is acompile time dependencyto the testing module.
|
I am runningjacocoplugin to generate html , xml andjacoco.execreports to measure the coverage of the code tested by mytestNgtests.I am successful in the generation of these reports in my local as well as inJenkinsand all my unit test results are reflected inSonarand it's showing me the coverage.Myjacoco.exechas both results of the coverage in the module and the dependent modules. I have verified this usingeclemma pluginforeclipse.I am not getting the coverage results in the dependent modules in Sonar.Does any one what I am doing wrong.My plugin goes like this<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.7.201606060606</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>and my goal isjacoco:report-aggregate
|
Aggregated Coverage or Coverage in the dependent modules not shown in SonarQube + Reports are generated by Jacoco
|
This was a bug in the previous sonar installations. But recently it is fixed and working fine. Try usingsonar Lintfrom eclipse market place (I hope you are using eclipse) which is the latest release of sonar in eclipse.I tried this code in my code base and the message is not displayed. So try updatingsonarorsonarqubetosonar Lint.
|
I think we have false positive in our Sonar's installation (5.6 and java plugin 4.0).
An Unused "private" method should be removed issue is raised for the following code :public boolean orderLineHasDetails(OrderLine orderLine) {
boolean result = orderLine.getContractDevices() != null && orderLine.getContractDevices().size() > 0;
if (result) {
result = asLeastOneUniqueId(orderLine.getContractDevices());
}
return result;
}
private boolean asLeastOneUniqueId(List<ContractDevice> contractDeviceList) {
Iterator<ContractDevice> contractDeviceIterator = contractDeviceList.iterator();
boolean result = false;
while (!result && contractDeviceIterator.hasNext()) {
result = StringUtils.isNotBlank(contractDeviceIterator.next().getDeviceUniqueId());
}
return result;
}Is this a known bug ?Thanks for your help.Edit:A new false positive inner a method :Regards,Stephane
|
False Unused "private" methods should be removed
|
sonarqube {
properties {
property "sonar.sourceEncoding", "UTF-8"
property "sonar.host.url", "https://a.com/"
property "sonar.login", "abc"
property "sonar.password", "abc"
property "sonar.projectKey", "abcd"
property "sonar.projectName", "ABCD"
property "sonar.projectVersion", android.defaultConfig.versionName
property "sonar.sources", "./src/main"
property "sonar.exclusions", "**/*test*/**,build/**,*.iml,**/*generated*"
property "sonar.tests", "./src/test/"
property "sonar.test.inclusions", "**/*test*/**"
property "sonar.import_unknown_files", true
property "sonar.java.lizard.report", "lizard/lizardReport.xml"
}
}Removed the extra quotation mark after the SonarQube host URL "https://a.com/“ --> "https://a.com/"eplaced the curly quotation marks (“ and ”) around the values of sonar.login and sonar.password with regular double quotation marks (")removed the extra space before property "sonar.java.lizard.report", "lizard/lizardReport.xml" for consistency.check the corrected properties are correctly placed within the sonarqube block in your build.gradle file.
|
I am trying to integratelizardto track the code complexity of an android app on sonarqube. The command used to get the complexity report from lizard is:lizard src/main -x"./test/*" -x"./androidTest" --xml >lizard/lizardReport.xmlIn thebuild.gradlefile of the app, the sonarqube properties are configured as follows:sonarqube {
properties {
property "sonar.sourceEncoding", "UTF-8"
property "sonar.host.url", "https://a.com/“
property "sonar.login", “abc” property "sonar.password", “abc” property "sonar.projectKey", "abcd"
property "sonar.projectName", "ABCD"
property "sonar.projectVersion", android.defaultConfig.versionName property "sonar.sources", "./src/main"
property "sonar.exclusions", "**/*test*/**,build/**,*.iml,**/*generated*"
property "sonar.tests", "./src/test/"
property "sonar.test.inclusions", "**/*test*/**"
property "sonar.import_unknown_files", true property "sonar.java.lizard.report", "lizard/lizardReport.xml"
}
}At the end of this setup, I am running thegradle sonarqubecommand to build the project and run the sonar setup but on viewing the report on the sonarqube dashboard, there is no trend for code complexity.Is there something I am missing here?
|
Sonar integration with lizard to track code complexity failing in android studio
|
The problem is solved by kind people from spring-mvc. More details can be found on the providedlink. In short, in my case Sonar uses Cobertura for coverage testing.Cobertura adds the interfaceHasBeenInstrumentedand because of that
the class is decorated as a JDK dynamic proxy instead, which means a
synthetic proxy class with one interface that's not very helpful since
it's a Cobertura marker interface. As a result and the controller can
never and no annotations can be properly discovered.The problem is solved by addingproxy-target-class="true"to<tx:annotation-driven>element
|
I have recently discovered Spring project for MVC testing:spring-test-mvc. It's a great tool, and I plan to use it more in the future.However I have noticed a problem with it on my Jenkins CI. The problem is that while MVC integration tests are passing locally, and even on Jenkins CI job, the problem occurs in the Jenkins' Sonar plugin execution. In this case all asserts done with ".andExpect()" method I tried fail. Yes, they pass if Sonar plugin is not used.For examplethis.mockMvc.perform(get("/someController/some.action").param("someParam", "someValue"))
.andExpect(status().isOk())
.andExpect(content().type(MediaType.APPLICATION_JSON))
.andExpect(request().sessionAttribute("someAttribute", notNullValue()));In the above test content type and session attribute assertions are failing.
Any ideas? Thanks in advance.
|
Problems with spring-test-mvc on Jenkins with Sonar
|
There seem toexista python plugin for sonar now.
|
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this questionWe are planing to place quality checking for our python code, earlier we used sonar for java projects. Is there any project support python having similar functionality of sonarsource ?
|
SonarSource Python alternative? [closed]
|
-1You can use annotation@SuppressWarnings("squid:S2187")
|
I am using Sonar 5.2 to analyze java project, tests written in TestNG.
I have test classes with @Test annotation on the class (not on methods).My tests are working fine (testNG treats all public methods as tests, no @Test annotation is required on each method), but sonar produces warningTestCases should contain tests (squid:S2187)If I put @Test annotation on methods, this warning disappears.It looks to me like false-positive (My class has test methods).
For testNG tests, squid:S2187 rule should be ignored if class has @Test annotation on class level and at least one public method.Is this indeed bug in squid:S2187 rule, or I am missing something?Edit:
I am using Sonar 5.2, java plugin 3.7
At the time of the writing (10 November 2015) my Sonar is up-to-date.
|
How to resolve false-positive sonar warning 'Add some tests to this class'
|
You can download the sonar-scanner tool fromsonarand run it in the project folder:sonar-scanner \
-Dsonar.projectKey=your-project \
-Dsonar.organization=your-org \
-Dsonar.sources=. \
-Dsonar.host.url=https://sonarcloud.io \
-Dsonar.login=8ed524debb4f53489e99bd66eb5110a3e8c2958ePersonally, I used my repositories pipelines to do the scan.
|
We have migrated our frontend project fromionic/es6/angulartoionic2/typescript/angular2. Everything is good except we don't know how to run sonar report on the project.Previously we are using gulp and rungulp sonarcommand to generate the sonar report (on an local sonar server).We don't use gulp in the new ionic2 project and wonder how to run the sonar scanner on the new project.Notewe have installed typescript plugin on our sonar server.we have addedsonar-project.propertiesfile in the project rood directoryQuestion is how to run itThanks...
|
How to run sonar scanner on an Ionic 2 project
|
You can use-Dsonar.scm.disabled=true. Seethis answerfor details.
|
During sonar runner analysis the SVN blame command is executed many times. Sometimes an error happens. The connection might be lost for a moment so that a timeout occurs and the SVN server can't be reached.The sonar-runner aborts execution when such a error occurs.Is it possible to configure sonar so that such SVN errors are ignored?
|
Ignore SCM Sensor error
|
Try to usesonar.coverage.exclusions.Assonar.coverage.exclusionsis Comma-delimited list of file path patterns to be excluded from coverage calculations. Your pattern should be like this:sonar.coverage.exclusions=com/abc/demo/presentation/beans/**/*, com/abc/demo/presentation/interfaces/**/*, com/abc/demo/presentation/validator/**/*, com/abc/utility/**/*Note: Documentation for this option was removed in 7.3 (Google:site:docs.sonarqube.org "sonar.coverage.exclusions"). But you can still see them when you open the administration pages for the project on Sonar -> "General Settings" -> "Analysis Scope". Look for the values after "Key:"
|
Is there any way to purposefully increase Code Coverage value in SonarQube by excluding some classes.
|
SonarQube code coverage - exclude some classes
|
You can change this array into aprivatevariable.Then add astaticmethod that returns a copy of this array, or an immutableListbacked by this array.For example:private static final String [] COLUMN_NAMES = new String[]{"date","customerNumber","customerName",
"account","emailAdress","mobilePhoneNumber","emailStatus"};
protected static List<String> getColumnNames() {
return Collections.unmodifiableList(Arrays.asList(COLUMN_NAMES));
}Or you can replace the array variable with an unmodifiableListinstead of using the method. That would be more efficient (since theListwill be created once instead of in every call to thestaticmethod):protected static List<String> COLUMN_NAMES = Collections.unmodifiableList(Arrays.asList("date","customerNumber","customerName",
"account","emailAdress","mobilePhoneNumber","emailStatus"));
|
I getting sonarQube error of below line, any suggestion experts how to resolve this? Thanks in advanceprotected static final String [] COLUMN_NAMES = new String[]{"date","customerNumber","customerName",
"account","emailAdress","mobilePhoneNumber","emailStatus"};
|
Mutable fields should not be "public static"
|
Decorating Pull Request is for Developer edition or above.But you can use unofficial releasesonarqube-community-branch-pluginInstall this plugin and then you can refer to documentation for further configuration.
|
Firstly I created SonarQube Server (Community Edition)
and I integrated sonarQube with Github for scanning the code of the GitHub.Then, I Created action in GitHub to run the sonarQube.github/workflows/python-pull.ymlrun: sonar-scanner
-Dsonar.host.url=${{ secrets.SONAR_URL }}
-Dsonar.login=${{ secrets.SONAR_TOKEN }}
-Dsonar.projectKey=${{ secrets.SONAR_PROJECT_KEY }}
-Dsonar.pullrequest.key=${{ github.event.number }}
-Dsonar.pullrequest.branch=${{ github.HEAD_REF }}
-Dsonar.pullrequest.base=${{ github.BASE_REF }}
-Dsonar.pullrequest.github.repository=${{ github.repository }}
-Dsonar.scm.provider=git
-Dsonar.java.binaries=/tmpThe result of GitHub actionsIn this image, It showed only "All checks have passed"Whenever I do push or pull in the GitHub so sonarQube server shows all the bugs, errors, Vulnerabilities, etc.Like thisBut my requirement is:I want all details of the code will display on the GitHub page which is shows in Sonarqube Server (Like bugs and errors)And also let me know that
Is it possible in the community Edition of sonarQube?
|
Decorating the pull request in GitHub with SonarQube (Community Edition)
|
Short answer: yes you can using the SonarQube Community IntelliJ pluginLong answer:assuming you have a build.gradle like:apply plugin: "sonar-runner"
sonarRunner {
sonarProperties {
// can be also set on command line like -Dsonar.analysis.mode=incremental
property "sonar.host.url", "http://your.sonar.server:9000"
property "sonar.analysis.mode", "incremental"
property 'sonar.sourceEncoding', 'UTF-8'
property 'sonar.language', 'java'
property 'sonar.profile', 'my_profile'
}
}
subprojects {
sonarRunner {
sonarProperties {
properties["sonar.sources"] += "src/main/java"
}
}
}
....then you can run local sonar analysis with gradle:$ ./gradlew sonarRunnerthis will produce a sonar-report.json file:$ cat build/sonar/sonar-report.jsonNow you have everything is needed by the plugin:SonarQube serverName: your_serverHost url:http://your.sonar.server:9000Local analysis scriptName: gradle scriptScript: /path/to/android-studio-example-project/gradlew sonarRunnerPath to sonar-report.json: /path/to/android-studio-example-project/build/sonar/sonar-report.jsonAfter the configuration is done you can see new issues by running the SonarQube (new issues) inspection inside Intellij (Android Studio)I have used this project for an example:https://github.com/sonar-intellij-plugin/android-studio-example-projectand sonarqube server 4.0 with a squid only based rule set (4.4 failed to analyse a gradle project)
|
Has anyone succeeded in getting either the SonarQube Community IntelliJ plugin OR the 'official' SonarQube IntelliJ plugin to show results of static code analysis in Android Studio projects?The second of these requires Maven but the first of these is supposed to be agnostic.Somehow I managed to run a sonarRunner on my project in the past but I can't manage to do it now. But there's not much point in getting that working again if I can't see my results in the IDE.
|
SonarQube plugin with Android Studio
|
You first test ifgetBody()returnsnull.SonarQube sees that and thinks the method can return null.Then, you call the same method again. SonarQube just knows that the method can return null so it tells you the warning.In other words, SonarQube thinks that it could return something different thannullthe first time but returnnullthe second time.If the method is just a simple getter and the object is not modified concurrently, this is no problem.In order to remove the warning, you can do one of the following:Save the result ofgetBody()to a variable, check if it is null and continue if it is notAdd a//NOSONARcomment telling SonarQube that you know what you are doing.Note that you might want to explain why this is ok in the comment, if you decide for the second case.
|
SonarQube reports this bug to me:A "NullPointerException" could be thrown; "getBody()" can return null.This is the code:if (holdingResponseEntity == null || holdingResponseEntity.getBody() == null || holdingResponseEntity.getBody().getError() || holdingResponseEntity.getBody().getResult() == null) { throw new HoldingNotFoundException("Holding whit id=" + idHolding + " not found-"); }
|
SonarQube - A "NullPointerException" could be thrown;
|
Finally I'm able to answer my own question with help of @benzonico's comment.In our CI system's Sonar build log I found many warning messages:[WARN] [16:51:48.435] Class 'com/bla/bla/Application' is not accessible through the ClassLoader.The bytecode analysis needs to get fixed for all classes and its dependencies in order to get a correct result. I had to set following Sonar properties:sonar.java.binaries=target/classes
sonar.java.libraries=target/dependency/*.jarNote that withoutsonar.java.binaries=target/classesit's not working, at least on our CI system (TeamCity).Before runningmvn sonar:sonarall Maven dependencies (transient ones too) are moved to the foldertarget/dependencyby runningmvn dependency:copy-dependenciesbefore the analysis now.Now the CI build log is cleaner, Lombok annotations get recognized.
|
I have recently updated SonarQube to version 4.5.4 and the Java plugin to version 3.5.We have classes annotated with@Data, but it seems that the rulesquid:S1068doesn't handle this "special" annotations. Altough they should be ignored since version 3.4 according tohttps://github.com/SonarSource/sonar-java/pull/257andhttps://jira.sonarsource.com/browse/SONARJAVA-990.Please see attached screenshot. Did I forget to configure something?UPDATE:I wanted to ensure that our used Java plugin 3.5 has included the changes of commithttps://github.com/benzonico/sonar-java/commit/5e7de16f59450061227d4103f64e351d1f93d9e9so I reverse engineered the .jar file to see the source of rulesquid:S1068UnusedPrivateFieldCheck.java. Extended Lombok releated changes are there and apparently working!
|
SonarQube 4.5.4 with Java plugin 3.5 doesn't recognize special Lombok annotations
|
Uncommented main methodis a CheckStyle warning that themain()method is not commented-out. You are not supposed to have debug/testmain()methods in your code.You can exclude your program entry point class using something like:<module name="UncommentedMain">
<property name="excludedClasses" value="\.Main$"/>
</module>See alsohttp://checkstyle.sourceforge.net/config_misc.html#UncommentedMain
|
I have been looking for this problem through google but it turns out I can not find a way to fix this problem. Actually I have a classicmainmethod in which I run a job, but sonarqube keeps repeating me there is an Uncommented main method found.Here is the code :/**
* Main : Run MapReduce job
*
* @param args
* arguments
*/
public static void main(String[] args) {
ExitManager exitManager = new ExitManager();
// run job
if (!runJob(args)) {
exitManager.exit(1);
}
}I do not see any particular problem here, so where does this problem come from ? Do you have any idea how I can fix this ?Thanks.
|
How to fix an Uncommented main method?
|
You have to use the "sonar.exclusions" property that is described in the documentation :http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-IgnoreFiles
|
My project has hierarchy as :test-my-project>src>com.adapter
>com.adapter.schema
>testI want to exclude com.adapter.schema package while running sonar.My sonar.properties is:sonar.properties/#required metadata
sonar.projectKey=test:prj
sonar.projectName=test-my-project
sonar.projectVersion=1.0
/# path to source directories (required)
sonar.sources=src
/# path to project binaries (optional), for example directory of Java bytecode
/# when you build the project, where the .class files are gone
sonar.binaries=build/classes
/# The value of the property must be the key of the language.
sonar.language=java
|
Can not exclude particular package from sonar runner(Sonar 3.3.1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.