Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
Instead of setting your DB configuration on the command line with system properties, consider setting them with profiles.Add something like this to your pom.xml:<profiles>
<profile>
<id>sonar</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.3</version>
<configuration>
<systemPropertyVariables>
<db.user>foo</db.user>
<db.password>bar</db.password>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>Documentation:http://maven.apache.org/guides/introduction/introduction-to-profiles.htmlhttp://maven.apache.org/plugins/maven-surefire-plugin/examples/system-properties.html
|
While executing Junit test cases on Eclipse we are passing VM arguments for DB configuration by-D, but while uploading the same Junit test cases to Sonar by Maven it's not working as no VM argument is set.I have tried to pass arguments byMAVEN_OPTSonMVN.shbut it's not working.
|
Pass VM argument for Database configuration -D for Junit test using Maven
|
Are you using the sqljdbc drivers to connect to SQL Server? I solved this issue by using thejTDS driveras detailed inthis answer.
|
When running Sonar 3.2 I get the following error message displayed when I try to list the projects analyzed in a web browzer.An error occurred while trying to display the widget "Filter". Please contact the administrator.when looking at sonars logs I see this message:rails Can not render widget filter: org.sonar.api.utils.SonarException: Fail to execute filter: Filter[rootSnapshotId=,baseSnapshotId=,baseSnapshotPath=,scopes=,qualifiers=[TRK],languages=,favouriteIds=,dateCriterion=,keyRegexp=,nameRegexp=,onDirectChildren=false,measureCriteria=[],periodIndex=0,sortedMetricId=,sortedByMeasureVariation=false,sortedByLanguage=false,sortedByName=true,sortedByKey=false,sortedByDate=false,sortedByVersion=false,isNumericMetric=true,ascendingSort=true], sql=SELECT s.id, MAX(s.project_id) as pid, MAX(s.root_project_id) as rpid, MAX(p.long_name) as name FROM snapshots s INNER JOIN projects p ON s.project_id=p.id WHERE s.status=:status AND s.islast=:islast AND s.qualifier IN (:qualifiers) AND p.copy_resource_id IS NULL GROUP BY s.idI am using SQL Server 2008 in the backend. The query doesn't look right for SQL. What could be wrong? When analyzing the project using Maven, I get no issues. It gives me a build success.I am using Apache Maven 3.0.2 and Sonar 3.2 on window. any clues about what is going on?
|
Sonar and Maven with SQL server on windows
|
I would suggest using the Sonararchitectural rules engineto find this kind of violation.
|
Recently, we were trying to write a PMD rule to spot all occurances of Spring JDBC template's query* methods. Looking at some sample AST xml code, I wrote the following innocuous XPATH expression.//PrimaryPrefix[Name[starts-with(@Image,'jdbcTemplate.query')]]But very soon, we realized that this is not adequate. If someone writes "this.jdbcTemplate.queryForObject" then "this" becomes the "Primary Prefix" and "jdbcTemplate" becomes the "Suffix". Also the variable name of the JDBCTemplate object instance could be anything.I thought it would be fairly easy to construct a XPATH expression to find out the occurance of a particular Class method call - anywhere in the code, but looking at the AST tree, I am just not able to figure it out. Is a XPATH really possible, or we have to write Java code?
|
Custom PMD rules for finding out method usages
|
It looks likethe newest version of the JavaScript plugin will support JQuery and NodeJS:New version of JavaScript plugin will be able to check jQuery and
NodeJS projectsedit:I was running version 0.4 of the JavaScript plugin.Version 1.0is the current version and it does seem to support at least JQuery.
|
Is there a way of adding JavaScript libraries to Sonar? I found that we can define undefined variables in 'General Settings' option, but couldn't find a way to tell Sonar that I have used a specific library like Backbone.js, jQuery, etc.I have used Sonar JavaScript plugin and everything else works perfect.
|
Adding JavaScript libraries to Sonar
|
The variable "resourceKey" probably doesn't point to a valid resource.The resource key for a project can be found on its main Sonar dashboard, in the description widget. For instance, on Nemo, you'll find the resource key for Struts 2 onits dashboard: "org.apache.struts:struts2-parent".If the resource is a file, then you have to append the resource path to its project key. For instance: org.apache.struts:struts2-core:org.apache.struts2.util.StrutsUtil
|
This is my first time using theSonar Web Service Java client. I've successfully downloaded the jar files and have had no errors executingSonar sonar = Sonar.create("http://localhost:9000", "login", "password");However when I execute:Resource struts = sonar.find(ResourceQuery.createForMetrics(resourceKey,"violations"));struts is null. I am not sure what I am doing wrong. Kindly ask me to add any additional information required.
|
Using Sonar Web Service Java client
|
AFAICT from:public final class NewCoverageFileAnalyzer {
public boolean shouldDecorate(Resource resource) {
return Scopes.isFile(resource) && !Qualifiers.UNIT_TEST_FILE.equals(resource.getQualifier());
}
}it looks like coverage of test files can't be shown in Sonar without changing the Sonar code.
|
I'm using:
Sonar version: 2.10
Emma version: 2.1.5320
Sonar Emma plugin version: 1.2I'm able to generate an Emma report showing coverage of the tests themselves (ideally this would be 100% but in practice it's not always), but Sonar shows only the coverage of the src files. How do I get it to show the coverage of the test files, too?Would switching to Cobertura help?
|
How to force Sonar to show coverage of test files?
|
-1It has worked for me: I am a beginner, so I didn't know - and the suggested manual recipe doesn't mention it - that local moderequiresa running SonarQube instance, working on this particular endpoint.So before you run SonarScanner locally, you need to have a local SonarQube server, at least with the default configuration of SonnarScanner.How to install SonarQube locally? Here is the instruction:Install the Server | SonarQube Docs.
|
When usingSonarScanneragainst a local source, following the suggested manual recipe for classic .NET and MSBuild, I find the following error (look at the bottom line):SonarScanner for MSBuild 5.5.3
Using the .NET Framework version of the Scanner for MSBuild
Pre-processing started.
Preparing working directories...
11:30:19.134 Updating build integration targets...
11:30:23.344 Failed to request and parse 'http://localhost:9000/api/server/version': An error occurred while sending the request.What's wrong? How to resolve this?
|
SonarScanner CLI error: failed to request and parse localhost:9000
|
-1You also need to add:sonar.dependencyCheck.jsonReportPath=target/dependency-check-report.json
|
I'm trying to run dependency check on sonarqube through jenkins using dependency check plugin. I'm able to generate report. but its not showing on sonarqube in vulnerability section. it says 0 vulnerabilities. I also installed dependency check plugin on sonarqube server. It is able to show the report on the dashboard if i pass the path of the dependency check. But i need to show vulnerability tab.
Following actions as below in jenkins atPost Stepssection
atInvoke Dependency check--project sample --scan target/*.war --format HTMLat Execute sonarqube scanner
sonar.properties analysissonar.projectKey=test
sonar.projectName=test1
sonar.projectVersion=1.0
sonar.sources=.
sonar.language=java
sonar.java.binaries=target/*
sonar.dependencyCheck.htmlReportPath=target/dependency-check-report.htmlon sonarqube dashboard all sections good like quality gateway, new bugs... but vulnerabilities shows zero. i have tried all the way but no luck
|
How to detect the depenency check vulnerabilities on sonarqube?
|
As you useBooleanand not the primitive typeboolean, you should not compare it with==. What you can do is:statusless == null || !statusless.booleanValue()
|
public List<LawOfficeDetailEntity> getLawOfficeByManagementUnitId(Long managementUnitId, Boolean statusless) {
List<LawOfficeDetailEntity> entities = lawOfficeDetailRepository.findByManagementUnitType(String.valueOf(managementUnitId));
return (statusless == null || statusless == false) ? entities.stream().filter(office -> office.getValidityStatus() == 1).collect(Collectors.toList()) : entities;
}I have "remove the literal "false" boolean value" sonar error on statusless == false. How can i fix it?
|
Remove the literal "false" boolean value
|
-1try something likesonarqube {
properties {
property "sonar.language", "java"
property 'sonar.exclusions', "**/ws/**/*.java"
}
}
|
I'm trying to exclude classes from a specific package from my gradle project so that sonar won't parse them.Seeing thesonar documentation for gradle, in the build.gradle file I have added the following:sonarqube {
properties {
property 'sonar.exclusions', "**/ws/**/"
}
}So that when passing the sonar in the project all the classes that are inside the / ws / package exclude them, but when executing the sonar, the classes have not been excluded.Is there a way to exclude packets in the gradle so that they are not parsed by sonar?Many thanks!
|
Exclude sonar classes in gradle
|
-1Your analysis is now based on the rules that are active in your SonarQube Quality Profile. You should re-create your rules in SonarQube.
|
After migratingmaven-checkstyle-pluginto SonarQube, I face some oddity how line feeds and tab chars are transfered.Back in my Maven build I had the following substantial rules:<module name="Checker">
<property name="fileExtensions" value="java, xml"/>
<!-- forbid dos/windows lf -->
<module name="RegexpMultiline">
<property name="format" value="\r\n" />
<property name="message" value="Do not use Windows line endings."/>
</module>
<!-- forbid tab character -->
<module name="FileTabCharacter">
<property name="eachLine" value="true" />
</module>
</module>While checking the SonarQube report I don't see these violations, where they should be. What am I doing wrong here?PS: SonarQube got this snippet as configured QG/QP.
|
SonarQube CRLF detection using checkstyle rules
|
-1As commented by Jeroen,this documentationdescribes how to connect to SQLServer.
|
I am installing SonarQube and created an AWS RDS Microsoft SQL Server instance.
How do I connect SonarQube to my rds instance with the endpoint?Sonar Properties file:sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonarsonar.jdbc.username=xxxxxsonar.jdbc.password=xxxxx
|
How do I connect SonarQube to my AWS RDS Microsoft SQL Server instance?
|
-1I've solved this by bypassing FxCop rules on the project.
|
Our .NET solution is compiling well fromMSBUILDcommand line. We're usingMSBuild.SonarQube.Runner.exefor Sonar Quality metrics which fails with messageEXECUTION FALIURE" during post processing. Log shows error message as
"INFO - MSBUILD : error MSB1009: Project file does not exist.Tried trace/debug level logging in sonar but nothing useful comes up. Post processing and compilation always succeeds. Only noticable point is that after above error line next line saysINFO - Switch:
D:\OurProject.sonarqube\out.sonar\q3techAMSUSProducerIVRGallery-Dev_AMSUSProducerIVRGallery_q3techAMSUSProducerIVRGallery-Dev_AMSUSProducerIVRGallery_397A5FDA-B454-4739-9A38-91810B9229DC\StyleCop-msbuild.projReffered stylecop file is present on disk, as well as we've tried disabling all stylecop and fxcop rules but nothing helps. If required log file can be shared.PLEASE ADVISE - Solution or Diagnosis Steps?
|
MSBuild.SonarQube.Runner.exe EXECUTION FAILURE with "MSBUILD : error MSB1009: Project file does not exist."
|
-1To make the answer available on stackoverflow as well:http://sonarqube.15.x6.nabble.com/Retrieving-the-key-of-a-quality-profile-tt5030042.html#a5030071
|
i want to get a list of all rules of a quality profile. In order to do that I first need to get the key (not the name) of this profile. Unfortunately this information can not be read by a simple ws call.
I'd be very happy if you could help me on this.Thanks,
Andreas
|
Sonarqube -how to get the key of a quality profile
|
-2Many times there are some problem with sync of sonar server and sonar lint ,it is not with this single issue , it is also replicated in other issues as well like duplicate code.refer sonar server and try to solve
|
Example code:public static String foo(){
return bar();
}
private static String bar(){
return "";
}SonarQube marks bar() function as unused, but SonarLint (IntelliJ, version 2.7.1.1640) works fine.
I have installed latest version of SonarQube (6.2) and latest version of Java plugin (4.5.0.8398), but still have this issue - i thought this issue was fixed?
Is this some kind of regression bug?
Thanks for your help.UPDATE:Above example was too trivial, i manage to specify problem: it looks like a problem with primitive arguments passed to function, for example this is marked as unused:public static String foo( SomeClass a ) {
return bar( a.getChar() );
}
private static String bar( char a ) {
return String.valueOf( a );
}if i pass hardcoded value to bar (like bar('a') ) everything works fine (or even when i pass something like bar("string".charAt(0) ) ). SomeClass.getChar() return 'char' so it is not a problem with boxing primitives.SOLUTION:
as @Michael - SonarSource Team suggested, there was a problem with dependencies bytecodes. I disabled teamcity Sonar runner plugin and now run sonarqube via Gradle plugin.
|
SonarQube false-positive "unused private methods should be removed" in static method
|
There are twodocumented optionsto exclude a module from a SonarQube analysis; quoting:You can either:use build profiles to exclude some module (like for integration tests)use Advanced Reactor Options (such as "-pl"). For example mvn sonar:sonar -pl !module2Since you are using Jenkins, maybe the simpler solution is to use the-ploption. This way, you won't change any configuration in your Maven project and you will only change Jenkins configuration.
|
I'm running sonar-5.1.2 with Maven / Jenkins CI.After googling and looking through similar questions (most of them are dated back to 2010-2012), it is still not clear how to exclude a particular Maven module from multi-module Maven project.Module Exclusionsproperty is deprecated since version 4.3 and should not be used anymore.We have duplicating packages in different modules:root pom.xml
|-module1
|-my.package.com
|-module2
|-my.package.comIs it possible to exclude only files frommodule2/my.package.combut includemodule1/my.package.com?SonarQube analysis is triggered byhttps://wiki.jenkins-ci.org/display/JENKINS/SonarQube+pluginpost build action
|
SonarQube exclude Maven module
|
I finally came out with the conclusion that the binary file (wrapper) is simply not compiled to run under HP-UXwhen launching afilecommand on wrapper under a Linux i get :<ELF-64 executable object file>which doesn't match the<ELF-64 executable object file - IA64>required by HP-UX running on a Itanium processor
|
I'm new to Sonar, and i was trying to install Sonar 2.8 on my server (Linux 64 on HP-UX)When i tried to launch it (sonar.sh start) i got the following message[myHomeDirectory]/sonar/2.8/bin/linux-x86-64/./wrapper: Execute permission denied.what drives me crazy is that i've putthe whole package on 777 permissions, so i really don't understand what's exactly happening.Can anyone help with this please ?Thanks in advance !
|
Can't launch sonar 2.8 (permission denied to execute wrapper )
|
First, this will not result in a compiler error. It's the usual case to multiply to int numbers and store the result in an int.A signed int if 32 bit wide can take numbers up to approx. 2 billion. If your code does what it says, this will make an update interval of 2 million seconds, or 23 days.If you really want to force a long-based calculation, just cast one of its factors:long updateInterval = millisecsPerSecond * (long) updateIntervalInSec;The second factor will get converted automatically then.Keep in mind that only casting the result will not be enough:private long updateInterval = (long) (milisecPerSecond * updateIntervalInSec);
// THIS WON'T DO AS EXPECTEDas it will do the problematic calculation on int and just cast the then maybe wrong result into a long.Casting is something that's described on the first three pages of every book on Java. If you're serious enough about code quality to run code quality tools, then have someone with knowledge of the language you use sit beside you. A trained pair of fresh eyes for a code review is such a great resource.
|
I am multiplying two numbers which is int and storing in long. But it displays error as ,
Cast one of the operands of this multiplication operation to a long. How to solve this?private int milisecPerSecond = 1000;
/**
* The update interval in seconds.
*/
// Update frequency in seconds
private int updateIntervalInSec = 5;
/**
* The update interval.
*/
// Update frequency in milliseconds
private long updateInterval = milisecPerSecond * updateIntervalInSec;
|
Cast one of the operands of multiplication operation to a long?
|
SonarQube is the central server holding the results of analysis.SonarQube Scanner /sonar-scanner-performsanalysis and sends the results to SonarQube. It is a generic, CLI scanner, and you must provide explicit configurations that list the locations of your source files, test files, class files, ...SonarQube Scanner for Gradle /./gradlew sonarqube-performsanalysis and sends the results to SonarQube. You don't have to provide explicit configurations that list the locations of your various types of files because it gets that from your Gradle project.
|
I'm using sonar & Jacoco for my Android application code coverage reporting. I could be successfully deploy it by setupjacoco taskjob &Sonar job& then following command../gradlew clean jacocoTestReport (name of jacoco task)
./gradlew sonarqube (<- mark this)Report is successfully generated and showing to localhost:9000 sonar server setup.I heard about sonar-scanner which is available to perform same task.My confusion is what I should usesonar-scannerorsonarqubewithgradlew command; How they mutually different from each other.
|
Difference between Sonarqube & SonarScanner
|
You could use Java 8 streams:assertTrue(permissions
.stream()
.allMatch(permission -> permission.getRole().equals("everybody")));
|
Currently I am doing thiswhile (permissions.hasNext()) {
assertEquals(permissions.next().getRole(), "everybody");
}This works fine, but is there a better way to do this ?Asking this since Sonar is currently showing a violation, saying "Add at least one assertion to this test case." I believe it is not able to read the assert inside the loop. Is this a bug in Sonar?
|
How to assert that all values in a collection have a certain property
|
Sadly, SonarQube does not fully support method-level metrics.However, you could give CodeAnalyzer plug-in a try:http://frontendart.com/products/codeanalyzer-for-sonarqube/McCabe's Cyclomatic Complexity is the metric your are looking for, I believe. I found an online demo for the plug-in (http://sonarqube.frontendart.com/), which does contain method-level McCC metric values.I hope this helps,
John
|
Apart from displaying complexity/function, can it be configured to display cyclomatic complexity of each method? This will help in quickly identifying potential refactoring candidates( methods) in large files with large number of methods.
|
Does sonarqube show cyclomatic complexity of a method?
|
The problem was the line endings. Changing the line endings to "Linux line endings" makes the problem disapear
|
I'm analyzing a PHP code using Sonarqube, and I've noticed that in almost all files I have this error:"Each PHP statement must be on a line by itself" (DisallowMultipleStatementsSameLine)But when I check this files seems that there is no error.For example, in this file the error is raised:<?php
/**
* Category of the question
*/
class Category {
public $categoryId;
public $name;
}
?>How can be?
|
“Each PHP statement must be on a line by itself” Sonarqube pattern error
|
The issue is that you are doingextra gymnasticson an operation that already produces aboolean.If I write out what you have coded in full syntax:boolean outcome;
if(count > 0){
outcome = false;
} else {
outcome = true;
}essentially, you are reversing thecount > 0So tryboolean outcome = !(count > 0)or even betterboolean outcome = count <= 0
|
I have the following nice one liner :boolean outcome = count > 0 ? false : true;But from sonaqube I get 'Remove the literal "false" boolean value'Thesolutionseems to assume you can re-write as a functionBut even that function will have that simple one liner and put me in the same position, I don't quite understand how to fix ? Ideas ?
|
Sonarqube : Boolean literals should not be redundant
|
You'll need to get the results into a format that SonarQube can interpret. Assuming you are using Jasmine/Karma this would be an LCOV format.Modify your build script to include the following line:ng test --code-coverageThis should create a coverage folder in your angular project. However it will be in an html format. You'll also need to change the Karma runner so that it generates an lcov.info file:// karma.conf.js
// ....
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['lcovonly'],
fixWebpackSourcePaths: true
},
// ....Finally, Update the sonar-project.properties file with the following line so that SonarQube knows where to find the coverage:sonar.typescript.lcov.reportPaths=coverage/lcov/lcov.info
|
This is my dahsboard from Bamboo related to Sonarqube:https://i.stack.imgur.com/FU7c9.jpgThe project build result page looks like this:https://i.stack.imgur.com/DRltU.jpgSo, I want enable somehow test coverage in Bamboo to see unit tests reports.
I mention that we have local coverage for my angular project.Can you help me with this?
|
How to "Enable front-end code coverage in sonarqube" for a Angular project
|
In the Makefile, you generate the coverage report using:go test -coverprofile $(package)/cover.out $(package)To generate the test report you need to add:go test -coverprofile $(package)/cover.out -json $(package) > $(package)/test-report.jsonOr if you prefer a single report, you can create an empty file:echo -n > test-report.jsonAnd append all the tests to it:go test -coverprofile $(package)/cover.out -json $(package) >> test-report.jsonNote: I removed-covermode=countbecause it's not useful if the report is only used by SonarGo.
|
How to generatego test -json > report.jsonGolang Version: Go1.10.3SonarQube Properties: sonar.go.tests.reportPaths = report.jsonOffical Sonar Document ->https://docs.sonarqube.org/display/PLUG/Unit+Tests+Results+ImportMakefile.PHONY: test
test:
@$(foreach package,$(packages), \
go test -coverprofile $(package)/cover.out -covermode=count $(package);)
.PHONY: cover
cover-xml:
@$(foreach package,$(packages), \
gocov convert $(package)/cover.out | gocov-xml > $(package)/coverage.xml;)
|
GoSonar : how to generate go test -json > report.json
|
Download SonarQube, unzip it and executebin/macosx-universal-64/sonar.sh consolein a terminal. Now open a browser, got tohttp://localhost:9000and follow the instructions.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Closed6 years ago.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.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.Improve this questionHow to install SonarQube as a service locally on my mac (os sierra 10.12.5)?
|
How to use Sonarqube as a service locally on mac? [closed]
|
A 79-element switch-case statement is practically always a bad sign. Not only is it duplicating a lot of similar code, it's also very hard to maintain. If you should ever need to change anything about it, I guarantee you will be mad at past you for not handling it differently.In this instance, if you have a number of String (Array?) properties that you want to have available by name and read from a file, a Map is by far the superior solution. No 10 byte memory difference will ever hurt you in such cases.
|
I have 79 cases in my switch.switch (field) {
case "ALL_STATUS":
allowedAllStatus = allowedValues.split("=");
break;
case "APPLICATION_TYPE":
allowedApplicationType = allowedValues.split("=");
break;
case "CONTACT_LOCATION":
allowedContactLocation = allowedValues.split("=");
break;
...When I ran my application to sonarqube, it asked me to reduce the number of cases:Reduce the number of switch cases from 79 to at most 30Now, at every case I need to perform the same functionallowedValues.split("="). Therefore, I decided to make a hashmap and put all the values from the cases right there and then call the function based upon the key field.Now, I want to ask if it is efficient to do it the way I'm refactoring it - memory wise or time wise?
|
Refactoring switch case to hashmaps: extra memory usage?
|
Use single quotes around the dash like so:uuid.lastIndexOf('-');
|
I get a Sonar major violation on the following method:private String getRequestId() {
final String uuid = UUID.randomUUID().toString();
return uuid.substring(uuid.lastIndexOf("-") + 1, uuid.length());
}Sonar advices me to useString.indexOf(char)when checking for the index of a single character since it executes faster thanString.indexOf(String).I get that.What I don't get is how to apply this advice on my code in an efficient way.
|
Best way to handle Sonar rule "Use Index Of Char"
|
Solution :Performance - Huge string constants is duplicated across multiple class files.1.Declare the class as final , make the field as public static final and assign inside static block.2.Dont Forget to declare private constructor otherwise sonar will show "utility classes should not be public or default constructor as (MAJOR issue)".public final class QueryConstants {
/**
* Default Constructor.
*/
private QueryConstants(){
//
}
public static final String COMMON_SELECT;
static {
COMMON_SELECT = "Your Query Here";
}
|
I am getting sonar vilation Performance - Huge string constants is duplicated across multiple class files.What is the reason i am getting this?
How to resolve this?This is the codepublic static final String GET_CO_ADMIN_GRID_DTLS ="A 30 line huge query";
|
Performance - Huge string constants is duplicated across multiple class files
|
I actually went back to look at this after you - it was still failing.
You were nearly there but I found two things:You had used JAVA_OPTS instead of ANT_OPTSCMSClassUnloadingEnabled is only used if you also use UseConcMarkSweepGC. See here:CMSPermGenSweepingEnabled vs CMSClassUnloadingEnabledSo the settings that seem to be working a treat now are:ANT_OPTS="-Xmx1024m -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:MaxPermSize=512m"UPDATE:Years later I have actually re-visited this again as the problem reoccurred. You don't actually need to mess with the GC settings, just the memory. The correct options to use are in fact:ANT_OPTS="-Xmx2G -XX:MaxPermSize=1G"Obviously you can tweak the memory values to suit your machine.Hope this helps others.
|
I'm getting the following error when running a build in antbuildcallbacks.xml:39: org.sonar.runner.RunnerException: java.lang.OutOfMemoryError: PermGen spaceIt's the part of the build where sonar runs over our code.Is there a way for me to know exactly where this error is coming from i.e is it the sonar server or the client etc ?Here is line 39 of my buildcallbanks.xml<sonar:sonar />EDIT: I've tried increasing the permsize from the wrapper.conf within Sonar and I still get the same issue no matter how high I set it. I must still be missing something?
|
Sonar java.lang.OutOfMemoryError: PermGen space
|
It is a false positive. SonarCube's rule is a bit "dumb". But you should be able to help it out ... something like this:GenericRes<?> body = response.getBody();
if (body != null) {
String message = body.getMessage();
if (message != null && !message.isEmpty()) {
return CompletableFuture.completedFuture(message);
}
}To my mind, that ismore readablethan the versions that SonarCube is having trouble with. So, that is a "win - win" solution.
|
I am facing one strange Sonar issue - A "NullPointerException" could be thrown.Below is my service implementation class. emailNotificationServiceClient is FeignClient Interface which works fine.try {
// send POST request
ResponseEntity<GenericRes<?>> response = emailNotificationServiceClient.sendEmail(payload);
// check response
if (response != null) {
if (response.getStatusCode() == HttpStatus.OK)
log.info("Email Send Successful : {}", response.getBody());
else
log.info("Email Send Failed : {}", response.getBody());
if (response.getBody() != null && response.getBody().getMessage() != null && !response.getBody().getMessage().isEmpty())
return CompletableFuture.completedFuture(response.getBody().getMessage());
}
} catch (Exception e) {
log.error("Error while sending email - sendEmailNotification in esb", e);
return CompletableFuture.completedFuture(e.getMessage());
}GenericRes class -@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class GenericRes<T> {
private String message;
private T data;
}I know that I have to add null check for object and then I should use that object. I have tried that but it won't work.I have also tried Java 8 Optional.ofNullable but still facing same problem.
|
try to fix SonarQube bug - A "NullPointerException" could be thrown
|
There are 3 approaches to solve the issue, I can think of.You can create a parent bean and extract the common attributes to it and then extend the 2 beans from the newly created parent bean, that way you will not get code duplication.You can exclude beans from sonar -- because beans are just beans and you don't have to really worry about doing a sonar analysis on them but still it still may be good to perform a sonar analysis on the beans too, depends on what you want to do. You can find details here on how to do it:SonarQube Exclude a directoryYou can change the order of the fields -- This is a dumb thing to do but I used to do it just to resolve the sonar issues.for example, if both files haveint a;
int b;
int c;
int d;change it toint a;
int c;
int b;
int d;this will trick the sonarqube
|
For two different ReST API I am getting different response with common fields present.I am creating two different bean for deserialization. Both beans have common fields present. Deserialization is working fine but sonar is giving issue that duplication block of code is present for the common fields.
|
How to resolve sonar issue - duplicate block of code?
|
Yes you can do thisSelect Analyze list and then choose Analyze VCS changed files with SonarLint
|
I am currently runningsonarlintplugin locally inIntelijwhich works well.I would like to run the pluginonlyfor files that I have in my Changelist - before I push them and create a Pull request.Is there a way to do this?
|
Sonarlint and Intelij: possible to run analysis only for files in a changelist?
|
The way Sonar Qube determines it's complexity is written down in theirdocumentation. The algorithm (if you want to call it) is "Count the number of certain statements".There are other algorithms to determine the complexity of a particular chunk of code, too. For example, there is the widely knownCyclomatic Complexity.
However, it doesn't really matter what you use as long as you are (within a project or company) all agree on a metric and a reasonable upper limit.And always remember that there are times when "the tool" is not right and the code in question is the right choice even if it's complexity is higher than the threshold. This can be for readability reasons or just for plain old performance optimization.
|
In my project we are using Sonar Qube which has limit for method complexity 10.If the method complexity is more than 10 then it raises major issues.Is there a standard which defines the method complexity?
|
What is the code quaility standard for method complexity in Java code?
|
This is just a warning from Sonar telling you that you are not conforming to java standards. In Java, it is standard to use camelCase for private variables. _ should only be used for static final variables.For example://Conforming private variable with camelCase
private String producerQueueName = "cn";
//Conforming private static final variable with "_"
private static final String PRODUCER_QUEUE_NAME = "cn";Sonar isn't telling you that youcan'tdo what you're doing, just that you aren't complying with the standards. This might make it harder for someone else to read your code.Seeherefor more details about java naming conventions.If you wish to disable the rule in Sonar, you will need to disable the rule in the Quality profile you are using. Seeherefor the documentation on how to do that.
|
private String producer_queueName = "cn";Name 'consumer_queueName' must match pattern '^[a-z][a-zA-Z0-9]*$'.Whats wrong with using_?
Does Java not allow you to use_for any variable?I want to use_. How can I get rid of this error:must match pattern '^[a-z][a-zA-Z0-9]*$'.
|
Sonar Complains about variable declaration..Cant we use "_"?
|
Define in your parent pom.xml the previous version of the plugin, it seems the latest version 2.7 has an issue you can pin the version like this :<pluginManagement>
<plugins>
:
:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>2.6</version>
</plugin>
</plugins>
</pluginManagement>
|
I see I am not the only one having this problem from 14 hours ago.At my office, other projects are failing too but the message shown make reference to sonar-maven-plugin:2.6:sonarorg.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.7:sonar (default-cli) on project x: Unable to determine structure of project.Any ideas?
|
Sonar Maven not working (org.codehaus.mojo:sonar-maven-plugin:2.7:sonar (default-cli)
|
You do not see any PMD rule repository because the java plugin reimplemented the PMD rules (not a 1 on 1 match).
For more details, please readthis.Please note the sonar-pmd-plugin is still supported. I advice to install a more recent version of the java plugin.If you specifically want to see the PMD rules, please install the PMD plugin
|
I have setup SonarQube Ver 4.3.3 , but when i navigate to Quality Profile -> Sonar Way with find bugs -> Coding Rules -> Repository i do not see any PMD rule repository.I can only see Common Sonar, FindBugs and Sonar Qube rule repositories.Does it means that my SONAR is not is not checking PMD rules ?
|
Why "Sonar Way with find bugs" has no PMD rule repository?
|
Yes, inManage Jenkins > Configure Systemyou can add as many Sonarqube installations as you want in the Sonar section. Then when you configure a job to perform the Sonar analysis you can select what instance you want to use from a drop down list.
|
Is it possible to configure Jenkins to use multiple Sonar instances?Currently we are using one Sonar instance for legacy projects (Java 6) and a new Sonar instance for Java 8
|
Single Jenkins instance using multiple Sonar instances
|
Yes, the Objective-C plugin for SonarQube is commercial:http://www.sonarsource.com/products/plugins/languages/objective-c/There is however an alternative free version on GitHub:https://github.com/octo-technology/sonar-objective-cI don't have any experience with either of them but maybe this helps.
|
I'm trying to research ability of SonarQube on our xcode project. I install every nessessary things: oclint, gcovr, xctool, sonar runner and sonar server. But when I build project to analyze by Sonar it throw exception like this:ERROR: Error during Sonar runner execution
ERROR: Unable to execute Sonar
ERROR: Caused by: No license for objcCan anybody understand why? I installed Objective C plugin in sonar server successfully but why it throw these exceptions? Thank you very much
|
SonarQube Objective C plugin is commercial?
|
As said above you can use Java6. Indeed youmustuse Java6.
When a sonar analysis is launched, the launcher of the analysis (sonar runner or maven) will use your sonar instance as a plugin repository. This means that each jar plugins will be downloaded on the machine performing the analysis. Then each plugin will be asked if it should be executed or not.
Hence, if a plugin is built using Java7, you need to run sonar using Java7 and you also need to run any analysis with Java7, even if this plugin is disabled.
|
I'm currently coding a plugin for sonar ( custom rules ) . Which JDK and API should I use in order to be compatible for teh majority of sonar instances ? JDK6 ?Thanks for your response
|
Which JDK's release should I use when coding a sonar plugin?
|
It almost feel that you omitted 'm' in your -Xms parameter:$java -Xms512 -version
Error occurred during initialization of VM
Too small initial heapWon't hurt to check values for other environment variables to see if there is anything Java-related defined ('set' command on Windows should print them all) - check _JAVA_OPTS, MAVEN_OPTS etc.
|
I'm using sonar and cobertura (for code coverage). I'm baffled with the problem I'm facing. If I runmvn sonar:sonarI saw the following error during executions[INFO]
[INFO] <<< cobertura-maven-plugin:2.5.1:cobertura (default-cli) @ hss-core <<<
[INFO]
[INFO] --- cobertura-maven-plugin:2.5.1:cobertura (default-cli) @ hss-core ---
[INFO] Error occurred during initialization of VM
Too small initial heap
[ERROR] Error in Cobertura Report generation: Unable to generate Cobertura Report for project.
org.apache.maven.plugin.MojoExecutionException: Unable to generate Cobertura Report for project.
at org.codehaus.mojo.cobertura.tasks.ReportTask.execute(ReportTask.java:93)if I run the cobertura plugin directly using the followingmvn cobertura:coberturaThere is no error as above, and display the following output, which I assume was the expected output.[INFO]
[INFO] <<< cobertura-maven-plugin:2.5.1:cobertura (default-cli) @ hss-core <<<
[INFO]
[INFO] --- cobertura-maven-plugin:2.5.1:cobertura (default-cli) @ hss-core ---
[INFO] Cobertura 1.9.4.1 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura: Loaded information on 39 classes.
Report time: 1035msI have set the MAVEN_OPTS (MAVEN_OPTS=-Xms512m) environment variable, but still getting the error.Can anyone tell me what went wrong, and how to fix this?
|
Error cobertura in sonar "Too small initial heap"
|
SonarSource is the company and SonarQube is one of their products. Theirpricingpage pretty much tells you want to want to know.You can host a SonarQube instance via Docker for free. Find the Docker imagehere.
|
I'm doing some research about Sonar but I am not able to understand the main difference betweenSonarQubeandSonarSource? And SonarQube is free or no? Because I'm not able to see the prices.
|
SonarCube Vs SonarSource
|
getPreAHistFltMsg extends Exception, which is a subclass ofThrowable;ThrowableimplementsSerializable, so all subclasses ofThrowablealso implementSerializabletransitively.Presumably,com.sanju.p2.GetPreAHistFltdoes not implementSerializable. As such, if you tried to serialize agetPreAHistFltMsgwhere that field is non-null, it would fail, because that field's value cannot be serialized.Either:Exclude the field from the serialization by making ittransient;MakeGetPreAHistFltimplementSerializable(but pay heed to theEffective Javaitem about why implementingSerializableis something that you should think carefully before doing);Extract the relevant (serializable) fields from it.
|
I am getting below bug after running sonarqube analysis i am getting errorMake "getPreAHistFlt" transient or serializable "How can we resolve this issue?code snippet:package com.sanju.p1;
//webfault and namespace
@WebFault(name = "getPreAHistFlt", targetNamespace = "http://www.getPreAuthorizationHistory")
public class getPreAHistFltMsg extends Exception {
private com.sanju.p2.GetPreAHistFlt getPreAHistFlt; // showing bug here
//constructors
public getPreAHistFltMsg() {
super();
}
public getPreAHistFltMsg(String message) {
super(message);
}
public getPreAHistFltMsg(String message, Throwable cause) {
super(message, cause);
}
public getPreAHistFltMsg(String message, com.sanju.p2.GetPreAHistFlt getPreAHistFlt) {
super(message);
this.getPreAHistFlt = getPreAHistFlt;
}
public getPreAHistFltMsg(String message, com.sanju.p2.GetPreAHistFlt getPreAHistFlt, Throwable cause) {
super(message, cause);
this.getPreAHistFlt = getPreAHistFlt;
}
public com.sanju.p2.GetPreAHistFlt getFaultInfo() {
return this.getPreAHistFlt;
}
}
|
sonarQube reporting bug - make field transient or serializable
|
Webhooks come out of the box starting with SonarQube version 6.2. Their purpose is to alert 3rd-party systems that the asynchronous processing of an analysis report is complete.Anticipated uses are:notifying your CI job or pipeline that the quality gate status has been computedposting fresh analysis results to a wallboard...
|
I came across Webhooks in SonarQube. I referred a documenthttps://docs.sonarqube.org/display/SONAR/Webhooks. But I didn't get for what webhooks can be used for SonarQube. As mentioned in the document I didn't seen webhooks in Administration > Configuration > General Settings > Webhooks. Do I need to add any plugin for that?
|
Purpose of webhooks in SonarQube
|
I think this is kind of false positive. Usage ofcom.sun.facesis an usage of internal implementation-specific classes but for JSF rather than JDK. Those classes will not be removed by other JVMs or some new version of JDK. You just bind your code to Sun's (Oracle's) implementation of JSF which might be OK or not OK for you.Looking into the code of that rule atGitHub, it looks like that it is configurable to avoid such false positives but setting theexcludeproperty as a comma-separated list. I am not sure where exactly you can do this in UI buthttps://docs.sonarqube.org/display/SONARQUBE50/Configuring+Rulesmight be a starting point.
|
On a Java web project (running on Tomcat & JSF & Spring), a custom renderer was written to get custom converters to be called even if the value to be converted isnull, as is explained here:JSF Custom Converter not called on null valueHowever, the SonarQube scan is detecting an issue on theimportline, namely:import com.sun.faces.renderkit.html_basic.TextRenderer;as it is acom.sun.*package and not a standard Java API package. The rule description states:Classes from "sun.*" packages should not be used (squid:S1191)Classes in thesun.*orcom.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. Similarly, they can cause problems when moving to a different Java vendor, such as OpenJDK.Such classes are almost always wrapped by Java API classes that should be used instead.Noncompliant Code Exampleimport com.sun.jna.Native; // Noncompliant
import sun.misc.BASE64Encoder; // NoncompliantThis makes good sense and all, but I can't find a Java API wrapper for this class, only the source code and packages that the class is in... What is the appropriate action to take in this case?
|
What Java API replacement exists (if any) for com.sun.faces.renderkit.html_basic.TextRenderer
|
I would strongly recommend against it,JLS-3.8. Identifierssays (in part)The "Java letters" include uppercase and lowercase ASCII Latin lettersA-Z(\u0041-\u005a), anda-z(\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or\u005f) and dollar sign ($, or\u0024).The$sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.
|
This question already has answers here:What is the meaning of $ in a variable name?(2 answers)Closed7 years ago.While I was going through one project I found some strange variables names. Sonarqube gaves me Code Smell statements about these variables.For exampleprotected String value$editedby$java$lang$String;And message from Sonarqube:Rename this field "value$editedby$java$lang$String" to match the regular expression '^[a-z][a-zA-Z0-9]*$'.So is it proper way to use$in variables names?
|
Is it proper way to set names of some variables using $ char? [duplicate]
|
Depending on your implementation ofgetContactDetails(), this method might returnnull, and so the linesyso(contacts.size());might fail due to an NPE becausecontactscould benull.Fix this by either addingif(contacts != null) {
syso(contacts.size());
} else {
// exception, error handling or nothing
}or by not returningnullingetContactDetails().
|
I have a method that returns list of contacts. When I am running this code on SonarQube server. It shows a blocker issue statingNullPointerException might be thrown as 'contacts' is nullable here.. How to resolve this?List<Contact> getContactDetails(){...}
public void checkSize() {
List<Contact> contacts = getContactDetails();
syso(contacts.size());
}
|
SonarQube Blocker Issue NullPointerException might be thrown as 'contacts' is nullable here
|
I was in similar situation and I created simple command line tool for copyingWon't FixandFalse-Positiveresolution types from one SonarQube project to another. A bit clumsy solution, you need to run it after each merge, but better than manually resolve the same issues in two or more SonarQube projects.You can find the tool on GitHub -https://github.com/HonzaTau/SqCopyResolution
|
I am using SonarQube to analyze my code before uploading to Gerrit and as a step in the review process in Gerrit. The same code is analyzed twice and I have two projects, e.g. "development-project" and "gerrit-project" in SonarQube. I then sometimes marks something as "Won't fix" or " False positive" etc in my "developpment-project". I would like to move that to the "gerrit-project". Is that possible?
|
Move "Won't fix" between projects in Sonarqube
|
Internal files, including web/**/*, must not be touched.To change JVM timezone, you should edit conf/sonar.properties and add the value-Duser.timezone=Europe/Sofiato propertiessonar.web.javaAdditionalOpts,sonar.ce.javaAdditionalOptsandsonar.search.javaAdditionalOpts.
|
I have a machine that runs several different servers and it's in a specific time zone in Central Europe.I need to run SonarQube (4.5.7) in UTC time.I uncommented the following line inweb/WEB-INF/config/environment.rband restarted SonarQube but the server still shows the original time zone on the System Info page.config.time_zone = 'UTC'Should that be enough to change the time zone in SonarQube? Because that didn't really work.Is there a way I can pass theuser.timezoneproperty to the JVM by editing thewrapper.conffile? Looks like it could work but it doesn't look like I'm supposed to touch that file.Thanks.
|
SonarQube: is it possible to change the time zone in the JVM parameters?
|
Other answers are partially right. Compiler must indeed be configured with -source 1.7 to check that no Java 8 lang features are used. But it does not prevent from using the new Java 8 APIs. A solution is to use the animal sniffer project to verify that only Java 7 APIs are used.Here is a a sample of configuration for maven projects:<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
<executions>
<execution>
<id>enforce-java-api-compatibility</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
<configuration>
<signature>
<groupId>org.codehaus.mojo.signature
</groupId>
<artifactId>java17</artifactId>
<version>1.0</version>
</signature>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
|
Since Java SE 7 isEOL, upgrading to Java 8 is necessary. However there are business reasons to not allow the developers to use any of the new language features. The feature that is especially forbidden is lambdas.How can the use of Java 7 features be enforced? The build system is based on Jenkins and there is also SonarQube available.
|
How to prevent Java developers from using new language features?
|
SinceDateis a mutable type, the code that passed you theDatecan continue to modify it after passing it to your function/constructor.So, instead of just assigning theDatepassed to you, you should instead make a copy of it to prevent this from happening:this.lastAccessTime = new Date(lastAccessTime.getTime());This is covered inEffective Java: Second Editionby Joshua Bloch asItem 39: Make defensive copies when needed.Note that you should make this copy before doing any validation on the Date as well.Edit: As noted below, a null check should happen before the copy to prevent aNullPointerException, but other validation should be done after making the copy.
|
This question already has answers here:Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object(8 answers)Closed5 years ago.I have the following in my code:
But why is this giving the Sonar error? Error is on line:this.lastAccessTime = lastAccessTime;The date here is already declared private.public class myClass{
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LAST_ACCESS_TIME", nullable = false)
private Date lastAccessTime;
/**
* Constructor
*
* @param userId the user id
* @param screenName the name of screen
* @param lastAccessTime time of last access
*/
public userTO(String userId, String screenName, Date lastAccessTime)
{
this.userId = userId;
this.screenName = screenName;
this.lastAccessTime = lastAccessTime;
}
}
|
May expose internal representation by incorporating reference to mutable object [duplicate]
|
Well ... this is indeed a mostly useless rule, especially because it cannot currently (5.7) be configured to enforce inner classes being declared at some other position than at the end. It can safely be disabled, I think.However, itisthe only way to enforce this part of the source file structure, so if you cannot be sure that everybody has her/his formatter properly configured, you might even want this. (Personally, I prefer inner types at the top, so that I know what they are when I read the code that's using them.)The Checkstyle rules were originally focused on theSun Code Conventions(1999), which did not say where inner classes should go. Also, the newer and popularGoogle Java Style(2014) has no opinion on this. Checkstyle even has aDeclarationOrdercheck, which also cannot check inner class position.So I guess someone finally said this had to end and addedInnerTypeLast. And there we have it. :-)
|
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.Closed5 years ago.Improve this questionI'm re-evaluating SONAR code quality rules after upgrade to 4.4 and here is strange CheckStyle rule called 'inner type last' which is part ofclass designgroup and actually recommends to place inner classes AFTER everything including methods.What motivation is behind this? I never expected someone to consider this approach as useful but maybe I have missed serious ideology? Checkstyle rule definition doesn't provide any ground neither quick googling (maybe I searched wrong way). Could you please point from where this comes?
|
What motivation is behind CheckStyle "inner type last" rule? [closed]
|
For developers to check their code prior to commit, they can use the Issues Report plugin for now. Seehttp://docs.codehaus.org/display/SONAR/Issues+Report+Plugin.
|
In our CI environment the SonarQube build breaker plugin is installed, and build will fail if Sonar scan alert threshold is reached. Developer needs to run SonarQube local analysis and fix any new issues and submit changes again.But this process does not work for javascript project. SonarQube Eclipse plugin does not support javascript yet, while maven sonar runner only generates a json file as the result. This is not user friendly to developer.So my question is: is there any other option to make javascript local analysis visualized besides installing local SonarQube server? Thanks.Best Regards,
|
Best way to run Sonarqube local analysis with javascript project
|
If the Sonar plugin is connecting to localhost that's an indication that it's using the default settings.Using Maven, there are several ways to configure Sonar.Jenkins pluginThesonar pluginfor jenkins is the simplest way to enable Sonar. Sonar properties are managed centrallyMaven settingsAdd the following profile to your Maven settings file ($HOME/.m2/settings.xml)<settings>
..
<profiles>
<profile>
<id>sonar</dev>
<activeByDefault>true</activeByDefault>
<properties>
<sonar.host.url>XXXXX</onar.host.url>
<sonar.jdbc.url>YYYYY</sonar.jdbc.url>
..
..
</properties>
</profile>
..
</profiles>
..
</settings>Read the following answer for an easy way to manage Maven settings files across multiple Jenkins projects:How to manage maven settings.xml on a shared jenkins server?Maven propertiesYou can set the Sonar properties within your POM as follows:<properties>
<sonar.host.url>XXXXX</onar.host.url>
<sonar.jdbc.url>YYYYY</sonar.jdbc.url>
..
..
</properties>Or import your sonar.properties file into your build using theproperties pluginI would favour one of the first two approaches. This option requires changing files within your project. Items like passwords should never be committed into revision control.
|
I am using maven's sonar:sonar goal to generate Sonar reports in one of my Jenkins job.My Jenkins host name is : jenhost.tst.com and My Sonar host is sonhost.tst.com and My Sonar jdbc url is : jdbc:mysql://sonhost.tst.com:3306/sonar, this database has a user names sonar created with proper permissions.Now While running the Maven goal, I am getting the error:Cannot open connection to database: Access denied for user 'sonar'@jenhost.tst.xxxx.com' (using password: YES)The weird thing in the above error is that the sonar user is trying to access my Jenkins host as a database name and not the sonar host.I have checked my Maven settings.xml and the database URL of Sonar is mentioned correctly there, and it is mentioned correctly in Jenkins too.Does any one have any clue regarding this one?
|
Cannot open connections to database. Sonar,Maven and Jenkins
|
Though the documentation says otherwise,I couldn't trigger cppcheck analysis from sonar.My solution was to launch cppcheck on its side, and then launch sonar-runner with report file parameter to import report to sonar dashboard:sonar.cxx.cppcheck.reportPath=C:\...\cppcheck_report.xmlYou may not need to precise this parameter if you generate the file at the expected place, WORKING_DIR/cppcheck-reports/ (not tested).
|
sonar doesn't launch cppcheck when I use sonar-runner.
I'm using the last version off all (sonar, c++ community pluguin and sonar-runner) in ubuntu 12.04.If someone has sonar working correctly with cppcheck (and the other plugins too, but now I only need cppcheck), tell me how please.In the sonar dashboard of the project appears the number of lines of code, comments, quality index, technical debt,... and the rules compliance appears at 100% and it's not true, because the project has cppcheck errors.
I'm sure that sonar doesn't launch cppcheck because running cppcheck takes 1-2 minutes, and sonar-runner shows 0ms in cppcheck section.Thank you!
|
Problems using C++ community plugin in sonar. Cppcheck doesn't work
|
Sonar does not currently handle incremental analyses.If you want, you can watch and vote for the following ticket:http://jira.codehaus.org/browse/SONAR-2815
|
I am using sonar for the last few months and want to know that do sonar works in an incremental way or not i.e if i do soanr analysis for the first time on my project code it will definitely analyze all the code but if i do some enhancement on my core source code and update some files then after updation do sonar analysis again on the same code then will sonar analyze all the files OR only analyze files which i have updated?
I am using "Sonar way with Findbugs" as my default quality profile.Is there any way to use sonar in an incremental way, to analyze only updated files?
Is this possible in sonar or not?Kindly revert your help will be appreciated..Thanks in advance..
|
SONAR - Analyzing source code in an Incremental way
|
The purpose of Sonar is to agregate results from all the core analysis engines (like PMD, Findbugs, Checkstyle), so that's why Sonar embeds all those tools, plus many more.So my advice would be to set up a continuous inspection server based on Sonar, and don't worry about any other tool as you'll get the best of all of them with Sonar.You can read the following blog entry about continuous inspection:http://www.sonarsource.org/continuous-inspection-practice-emerges-with-sonar/
|
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.Closed10 years ago.Improve this questionNow, we have a lot of tool for static code analysis in java.For example:PMDCPDFindBugsCheckStyleSonarJDependetc.Is it good to use all these tools in one application (using maven we will fail the build in case of negative scenarios). Are they interchangeable or they check approximately the same? Or it will be just excess?
Maybe there are some categories for these tools?
|
Using a lot of static analysis tools in one application [closed]
|
I'm assuming that you're referring toSonar from Codehaus, and notSOund Navigation And Ranging.From theinstallation page:The Sonar web server requires 500Mo of RAM to run efficiently.In terms of data space and as an indication, on Nemo the public instance of Sonar, 2Go of data space are used to analyze more than 6 million LOC with an history of 2 years. For every 1'000 LOC to analyze the database stores 350 Ko of data space.
|
It might looks like a dumb question. In fact it's more like a poll: how big is your Sonar database? I need this to estimate the requirements for a virtual machine to host my Sonar instance.Also:how big is your team?how many additional bytes is used in the Sonar database for every new commit?I will appreciate any help.
|
How big is a sonar database?
|
the reason is here:Integer a = -1;
Integer b = Integer.MIN_VALUE;
System.out.println(b); // -2147483648
System.out.println(-b); // -2147483648
System.out.println(a); // -1
System.out.println(-a); // 1If you want to use the result of compareTo to judge, for example:Integer a = x.compareTo(y)
if(-a > 0) {
//do something
}If the return value ofcompareToisInteger.MIN_VALUE, then the value of-ais equal to the value ofaboth are-2147483648, so the result is wrong
|
I am using SonarQube. There is aruleagainst java language:It is the sign, rather than the magnitude of the value returned from
compareTo that matters. Returning Integer.MIN_VALUE does not convey a
higher degree of inequality, and doing so can cause errors because the
return value of compareTo is sometimes inversed, with the expectation
that negative values become positive. However, inversing
Integer.MIN_VALUE yields Integer.MIN_VALUE rather than
Integer.MAX_VALUE.The problem is SonarQube consider this a bug, not code smell. Under what circumstances would this cause an error?Can anyone give a example ?
|
Why compareTo should not return Integer.MIN_VALUE
|
In general please have a look at the SonarQube rule descriptions to understand what they mean, whether they are relevant for your usecase and how to fix the issues. In this case therule descriptionshows how this can be solved:// since Java 8, we can use Supplier, which will be evaluated lazily
logger.log(Level.SEVERE, () -> "Something went wrong: " + message);orif (LOG.isDebugEnabled() {
// this is compliant, because it will not evaluate if log level is above debug.
LOG.debug("Unable to open file " + csvPath, e);
}It depends on the logging framework you are using which of these solutions is possible.
|
My code looks like:logger.debug("Message:Request", new Gson().toJson(req));Sonar issue says:Invoke method(s) only conditionally.How do I fix this line of code?
|
How to resolve Sonar "Invoke method(s) only conditionally"
|
You need to do this:try (Stream<Path> list = Files.list(voucherDirectory)) {
lastFilePath = list
.filter(f -> !Files.isDirectory(f))
.max(Comparator.comparingLong(f -> f.toFile()
.lastModified()));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
|
I am having trouble to apply the suggested method by Sonarqube scan in this line of code/method.Sonarqube says,"Use try-with-resources or close this "Stream" in a "finally" clause."Files.list(voucherDirectory)@Override
public String getLastModifiedFile() {
Path voucherDirectory = Paths.get(vouchiDir);
Optional<Path> lastFilePath = Optional.empty();
try {
lastFilePath = Files.list(voucherDirectory)
.filter(f -> !Files.isDirectory(f))
.max(Comparator.comparingLong(f -> f.toFile()
.lastModified()));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
if (lastFilePath.isPresent()) {
return lastFilePath.get().getFileName().toString();
}
return "none";
}Any help is really appreciated!
|
Use try-with-resources or close this "Stream" in a "finally" clause
|
Yes, usingaddressofonstd::coutis safe. But since using&onstd::coutis equally safe, the only reason to do it is to quiet a tool that clearly is giving you a false-positive (that it, it doesn't realize whataddressofis doing).It would be better to use&and employ whatever mechanisms exist in the tool to turn off false-positives.
|
I am usingstd::coutfor logging and sonarqube reports error when "Don't take the address of 'cout', call it from a lambda instead".std::ostream *streamp;
streamp = &std::cout;When I use the below code there is no error observed in sonarqube. Is usingstd::addressofonstd::coutfunction safe?std::ostream *streamp;
streamp = std::addressof(std::cout);
|
is there any risk using std::addressof(std::cout) instead of &std::cout?
|
Well, you're operating on an array of known length and add all elements to the set. Assuming you don't have any duplicates the resulting set should contain the same number of elements.However, you're creating a set with a default initial capacity, i.e.new HashSet<>(). That might cause the need for the set to be resized which isn't a problem in itself but would be unnecessary and thuscouldcause some performance hit.To get rid of that, create the set vianew HashSet<>(jsonArray.length())right before iterating.
|
Sonar shows that me this bugPerformance - Method does not presize the allocation of a collectionMethod mapping(ResponseEntity) does not presize the allocation of a
collectionHere is the code:private Set<ResponseDTO> mapping(ResponseEntity<String> responseEntity) {
final Set<ResponseDTO> result = new HashSet<>();
final JSONObject jsonObject = new JSONObject(responseEntity.getBody());
final JSONArray jsonArray = jsonObject.optJSONArray("issues");
for (int i = 0; i < jsonArray.length(); i++) {
final JSONObject innerObject = jsonArray.getJSONObject(i);
final String name = innerObject.optString("key");
result.add(new ResponseDTO().name(name));
}
return result;
}Why does Sonar flag this as an error and how can I fix it ?
|
Method does not presize the allocation of a collection
|
So how does it use Jacoco report? And why does it need it?SonarQube itself alone doesn't / can't know anything about which tests you actually executed and how they cover your code. To obtain this information it relies on third-party test coverage tools. In case of Java it relies on data collected and provided by JaCoCo asexplained in answer on similar question from you(JaCoCo collects execution information inexecfile, and obtains line numbers and other information fromclassfiles during generation of report), or SonarQube can rely on data in"generic format".
|
JaCoCo just outputs jacococ.exec which is the input for Sonar. In that file, there seems to be only the info:- Class name
- Total Class Probes
- Executed Class ProbesBut then, SonarQube cannot rely solely on these values as it needs to tell you which are the exact lines unconvered, so Sonar is performing an analysis on itself. So how does it use Jacoco report? And why does it need it?
|
How does SonarQube calculate coverage through JaCoCo?
|
You cannot run SonarQube as root. It was never a good idea to do that - now SonarQube will not even start.The dashboard has been replaced by new and more powerful project pages.
|
I have few queries regarding SonarQube 6.7 (LTS)1) If I start the sonarqube service with root account from Ubuntu machine, it fails with below error.Error messageFrom SONARQUBE_HOME/logs/es.log it was showing error as below:2017.11.09 08:42:29 ERROR es[][o.e.b.Bootstrap] Exception
java.lang.RuntimeException: can not run elasticsearch as root
at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:106) ~[elasticsearch-5.6.3.jar:5.6.3]However, with a non-root account I was able to start the service and it is working fine now. So is there any way available to use root account to start the service? If so let me know the same.2) Dashboard and Configure Widgets options not showing in this version, Are these options removed from this version? Please let me know.
|
Queries regarding SonarQube 6.7 (LTS)
|
High availability is the main focus of theData Center Edition. To archieve this level of availability, you run a cluster of five SonarQube instances. If one of those nodes crashes (power shortage, network issue, etc), SonarQube will still be available.However improvements have also been made in the core of SonarQube, makingalleditions more stable and more reliable.
|
According to theSonar roadmap for v6.x, support for huge instances was planned, including "High Availability". SonarQube 6.7 was released today with no mention of High Availability, should we conclude it was postponed to SonarQube 7.x?
|
High availability in SonarQube LTS 6.7
|
Jenkins and SonarQube do not have to be on the same machine.The SonarQube plugin in Jenkins will run one of these three scanners:SonarQube ScannerSonarQube Scanner for MavenSonarQube Scanner for MsBuildDepending on which scanner you use, it works a bit differently:For the SonarQube Scanner, pass-Dsonar.host.url=http://your.host:1234as additional arguments. (or add it to yoursonar.propertiesfile)For the SonarQube Scanner for Maven, add-Dsonar.host.url=http://your.host:1234toyour maven build step.For the SonarQube Scanner for MsBuild, add/d:sonar.host.url=http://your.host:1234to yourMsBuild.execall.
|
I am trying to run a SonarQube scan from Jenkins job. I have the SonarQube Scanner for Jenkins plugin installed v2.6.1 running on local Jenkins (for dev only);I have seen conflicting reports on whether or not youcanrun SonarQube on a different server then Jenkins. It wouldn't make sense if youcould notdo that... if you can, instructions on how to accomplish it would be great. Simply putting in the URL to the SQ server where Jenkins expects a directory to Sonar Runner locally, does not work.
|
Do Jenkins and SonarQube need to be on the same machine?
|
No, it is not possible to transfer Issues from one SonarQube instance to another.As Jeroien Heier pointed out in a comment, the most reliable and elegant solution to your problem would be to have the plugin compatibility fixed.
|
I have a plug-in that I really like that isn't supported in the latest LTS release of SonarQube. So I want to host an older version of SonarQube to use this plug-in to find issues, and then forward those issues to the newer version of SonarQube.Is this possible?
|
Can I forward issues from one SonarQube instance to another?
|
Thing is: usingEnumMapis good practice, therefore SonarQube tells you to do so.But you explicitly choose to use aLinkedHashMap- which keeps track of insertion order.So that message could be interpreted as:when you only care about mapping enums, use EnumMapwhen you need to map enums and care about insertion order, you have to stay with the ordinary LinkedHashMapIn other words: keep in mind that such tools are justtools. They provide messages tohelpyou making informed decisions. When you decided that your current implementation is fine - then don't change your code, just because some tool puts up such "advise".
|
I might miss something, but declaring a LinkedHashmap:private final LinkedHashMap<anEnum, anInteger> linkedHashMap;and later:linkedHashMap = new LinkedHashMap<anEnum, anInteger>();results in:"Maps with keys that are enum values should be replaced with EnumMap"
(SQUID: 1640)Since there is no "LinkedEnumMap", this declaration should be ignored.
|
(SonarQube) LinkedHashMap and S1640 (tells you to use an EnumMap)
|
I think you have to clear existing sonar files (existing sonar files) from your work space and build you project again.In your workspace sonar folder might be created which contain sonar file open that folder and remove all files present folder/files.
|
I upgraded my sonarqube from 5.6 to 6.4 with plugins according tosonarqube compability matrix. But after that errors such asthis onestarted appear duringgradlebuild. I set propertiessonar.java.binaries=**/build/classesandsonar.java.binaries=**/test/classesand now build is successful, but project is not updated in sonarqube after scan.Did anyone face with this issue? How can it be checked?UPDATE:I removed the next parameters fromgradle.propertiesand now it works fine:systemProp.sonar.sources
systemProp.sonar.tests
systemProp.sonar.test.inclusions
systemProp.sonar.exclusion
|
Project is not updated in sonarqube after scan
|
This specific behaviour is a common symptom of a corrupted Elastic Search index (no longer in sync with SonarQube database).SolutionRebuild the SonarQube ElasticSearch index:stop your SonarQube serverdelete the ElasticSearch index @sonar_install_dir/data/esstart your SonarQube server(reminder:ElasticSearchis a search engine used by SonarQube to index issues, rules etc. so that it can access this data rapidly without having to query the database all the time, seeSonarQube Architecture)Root-causeWhy did that happen ? A common case is an ElasticSearch index not being properly rebuilt after upgrading and/or changing database. Here's a typical scenario: you first start SonarQube on embedded H2 database, experiment a bit with it, then plug it to a full-fledged database. If the ElasticSearch index does not get scratched/rebuilt in between, then the index gets corrupted as the database/dataset it used to be in synch with just changed all of the sudden.FYI there's an improvement planned to handle this more gracefully:SONAR-5681.Note: independently from above solution, do not take ElasticSearch index rebuild as a lightweight operation that should be performed regularly. SonarQube does self-manage its ElasticSearch index, so any issue must be investigated first.
|
I have upgraded sonarqube server from 6.2 to 6.3.1 and since then I see a weird behaviour regarding the quality profile (it might have occurred before, it is only now I see it).When I click on the Quality ProfileSonarWay(Java) I seeso it seems, that all rules are inactive.When I clickActivate MoreI see the followingso it looks, that there are rules are active (I assume due to the "Deactivate" option").But when switching in the left bar to "active" underQuality Profileresults in thisso clearly, no rules are active.What is the second image then showing, what does the "Deactivate" mean, although it is inactive ?How could this happen that suddenly all rules seem to be inactivated ?
|
Quality profile weirdness (active/inactive rules) after sonarqube upgrade 6.3.1
|
We can also exclude the files using maven.<properties>
<sonar.exclusions>org/binarytherapy/generated/**/*,Mostly we use the following(I recomend this approach)
Administration > General Settings > Analysis Scope > FilesIn rare cases we use sonar-project.properties for exclusions.references:Configure Sonar to exclude files from Maven pom.xmlhttps://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus
|
I am playing around with the ready to useSonarqube Version 6.2andsonar scannerwith asonar-project.propertiesfile based on the tutorial @https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner.I am curious about the exclusions. I am still using the embedded databases (not a full install), and I have gone to Administration>Configuration>Exclusions and set the followingconverage exclusions-**/*.js, and**/target/**.However when I run the project throughsonar scannerthe JS files are still being analyzed.I saw on another page in anarchivethat there is a properties file parametersonar.exclusions.Question: Does sonar respect the general settings > Analysis scope when analyzing through the scanner or should I use the project properties file?What is the proper approach?
|
Sonar Exclusions - Project properties file or General Settings
|
Your methods are too short to show up as duplicated.Per the docs,There should be at least 10 successive and duplicated statements whatever the number of tokens and lines.
|
Am trying to show someone over here how good I find the sonar
tool...
then I wrote a small java project and defined many intentionally smelly methods,
2 of those are exactly the same (copy+paste)do1anddo2surprisenly, after running the sonnar, there is no duplication error nor warnings...public void do1() {
for (int i = 0; i < 10; i++) {
if (i != 0) {
System.out.println("Hello");
System.out.println(new Date());
}
}
}
public void do2() {
for (int i = 0; i < 10; i++) {
if (i != 0) {
System.out.println(new Date());
System.out.println("Hello");
}
}
}what is the criteria for a java project to raise a warning on duplicates then?
|
Sonar Duplication is not working as expected?
|
The rule exists:https://sonarqube.com/coding_rules#q=S138It's not activated by default in SonarLint, though.To use it, you need to bind SonarLint to a project in a SonarQube server which has that rule activated. You can also costumize the number of lines needed to trigger it.
|
I am new to sonarLint I have tried it out and I am asking myself, if this tool can check the number of codeline of java method. It should print an error, if a method has more codeline than for example 80 lines. Is this possible?
|
how to make SonarLint check for number of code line in java method
|
However if I clone the object and later on if I want to update the value then how can I access the original object because I have returned the cloned objectYou don't. At least not from the caller.I'll go out on a limb here and say we're talking about a list, so:public class MyClass {
private List<String> strings;
public List<String> getStrings(){
// returns a copy, so member list is still intact
return new ArrayList<String>(strings);
}
public void addString(String newString) {
strings.add(newString);
}
public void dropString(String oldString) {
strings.remove(oldString);
}
public void replaceString(String oldString, String newString) {
dropString(oldString);
addString(newString);
}
}In other words, you control access to member actions through the owning class. If you truly want a public member that anyone can get and update (not that I recommend that) then drop the getter and make the memberpublic.
|
When I do a sonar scan I get the vulnerability "Mutable members should not be stored or returned directly". The resolution for this is also provided where it is mentioned that we should clone the mutable object or return unmodifiable list.
However if I clone the object and later on if I want to update the value then how can I access the original object because I have returned the cloned object?
Any thoughts on this will be appreciated. Thanks in advance
|
Sonar scan - Mutable members should not be stored or returned directly
|
It's not shocking that you got some issues using SonarQube Scanner to analyze your C# project. But did you getallthat you should have?When you analyse with the SonarQube Scanner, you're basically doing a file by file analysis. So each source file is analyzed on its own without any information about the types that are defined in other source files. There are other differences too. For example each partial part of apartial classis also analyzed separately. As you can image this can only be done on a best effort basis, and will result in missing or inaccurate issues.Comparatively, when you use the Scanner for MsBuild, the analysis is integrated into your build process. So the analyzers can use all type information available to the compiler. Naturally, this results in lot more accurate issues, code coloring, ...This is why the SonarQube Scanner for MSBuild is recommended for the analysis of .NET projects.
|
I'm trying to setup a Sonar scan for C# code and from the documentation I understand that sonar scanner is deprecated and I have to use MSBuild for C#.
But in the meantime I managed to run a sonar scanner analysis on the C# code and also got some issues too. So the scan seems to be successful.My question is: Is it worth to make the transition from sonar scan to MSBuild scan and why?
I'm asking this because making this change would require some effort, time and resources which I would rather spare if possible.
|
Sonar scanner vs. SonarQube Scanner for MSBuild
|
In my child project, I have:apply plugin: 'java'
apply plugin: "jacoco"
jacocoTestReport {
reports {
xml.enabled = true
}
}
check.dependsOn jacocoTestReportRun Gradle task "sonarqube" of the root project.
|
I have multi-project Gradle script. I added to the root project:buildscript {
repositories{
...
}
dependencies { classpath("org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.2.1") }
}
apply plugin: org.sonarqube.gradle.SonarQubePlugin
sonarqube {
properties {
property "sonar.junit.reportsPath", "$projectDir/build/test-results/test"
property "sonar.host.url", "http://localhost:9000"
property "sonar.verbose", "true"
}
}Sonarqube shows the correct number of tests, but coverage is 0.I use Gradle 3.0, Java 1.8.0_45, Sonarqube 6.1.Gradle console shows many "Class not found" messages.Gradle console also shows message:"Reports path contains no files matching TEST-.*.xml :
myPath\build\test-results\test", which is correct, since that particular project does not have any tests.
|
Sonarqube task in Gradle does not produce test coverage
|
I would recommend using a build tool like maven or gradle. There you can find plugins which do the trick for you.Gradle plugins
|
I already search on Google and Stackoverflow about this Question, and don't have any answer that related to this kind of question.So the problem is, I have a Project with Spring MVC. I create simple test like this:@Autowired
private UserLogicService logicService;;
@Test
public void helloTrue(){
//return should be 1
assertThat(logicService.hello(), is(1)); //test return success
}
@Test
public void helloFalse(){
//return should be 1
assertThat(logicService.hello(), is(2)); //test return fail
}And then I need to export it to XML because I read the documentation of SonarQube,HERE, The tests execution reports have to comply to the JUnit XML format.I use SonarScanner third party to Scan my Spring Project. So I need to Export my JUnit result as XML and scan it with SonarScanner.Is there any Setting to Automatically export JUnit Test Result to a folder as XML file?
|
How to Export JUNIT Test Result as XML in Spring Boot Application for SonarQube Purpose?
|
Your httpd configuration is incorrect. Here is the snippet you should set to make the reverse proxy working correctly.RequestHeader set X-FORWARDED-PROTO "https"
ProxyPass "/" "http://my.sonarqube.com:8082/"
ProxyPassReverse "/" "http://my.sonarqube.com:8082/"If you want to prevent issue with BREACH and CRIME attack, remove the SSLCompression :SSLCompression offYou should also check which SSL protocol you want (you should allow only TLS) withSSLProtocoldirective and the ciphers you want withSSLCipherSuitedirective.
|
I would like to have Sonarqube 5.2 (https://my.sonarqube.com) configured as a secured connection and behind a reverse proxy, but it doesn't work.
I installed mod_proxy and mod_ssl.In httpd.conf<VirtualHost *:80>
ServerName my.sonarqube.com
Redirect permanent / https://my.sonarqube.com/
</VirtualHost>
<VirtualHost *:443>
ServerName my.sonarqube.com
SSLEngine on
SSLCertificateFile /etc/ssl/sonarhosting.pem
ProxyRequests Off
ProxyPreserveHost On
AllowEncodedSlashes NoDecode
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass / http://my.sonarqube.com:8080
ProxyPassReverse / http://my.sonarqube.com:443
RequestHeader set X_FORWARDED_PROTO 'https'
RequestHeader set X-Forwarded-Port "443"Is there anyone who can help me please?
|
Setup Sonarqube behind a reverse proxy on RedHat
|
Asstated in the documentation, you need toCreate an empty schema and a sonarqube user. Grant this sonarqube user
permissions to create, update and delete objects for this schema.Given that schema and the proper permissions to it, SonarQube will indeed create its own tables, indexes, &etc. And since you're going to carefully restrict the sonarqube user's permissions to only the sonarqube schema, there should be no question of interfering with existing tables or data.
|
I’ve experimented with SonarQube 6.0 using the H2 default database
and now I wanted to see how we can configure it with oracle 11
database.I’ve tried the followingdocumentationbut it is not clear what
tables (schema) would be created on oracle DB. Does it need its own
separate DB or I can connect it to our own existing DB ? If the
latter one is right and SonarQube automatically creates the tables, i
wanted to make sure it won’t drop any tables or data (for
e.g if they have a script that would drop tables and recreate them.I know this is unlikely to happen but we had one plugin in the past
that did something like that and I wanted to be cautious ).I appericiate if you can guide me with the steps. I’ve already configured the sonar.properties file to point to our current DB.sonar.jdbc.username=bdr
sonar.jdbc.password=dev1pass
sonar.jdbc.url=jdbc:oracle:thin:@dev3.our.domain.com:1522:dev3Thank you!
|
How to setup SonarQube 6 with Oracle Database
|
The ability to create manual issues has been removed in SonarQube 5.5 :https://jira.sonarsource.com/browse/SONAR-7472
|
In my web_api page ( EX: http://'my-site-name'/web_api/api/issues ) I can’t find any api for creating an issue.I can see other apis like Assign/Unassign an issue,api/issues/add_comment,api/issues/delete_comment etc .
While trying the following method, I have got the error message like this
curl -X POST -v -u admin:admin 'http://localhost:9000/api/issues/create?component=myproject:myfile&rule=manual:performance&line=2&severity=BLOCKER&message=blabla'{"err_code":404,"err_msg":"No action responded to create. Actions: actions, add_comment, admin_required, authorized?, available_locales, bulk_change, changelog, current_user, current_user=, delete_comment, edit_comment, error_to_json, error_to_xml, format_datetime, handle_remember_cookie!, has_role?, is_admin?, is_user?, java_facade, json_not_supported, jsonp, kill_remember_cookie!, load_resource, logged_in?, login_from_basic_auth, login_from_cookie, login_from_session, login_required, logout_keeping_session!, logout_killing_session!, parse_datetime, redirect_back_or_default, render_access_denied, render_bad_request, render_error, render_java_exception, render_not_found, render_response, render_success, resource_required, select_authorized, send_remember_cookie!, store_location, text_not_supported, transitions, valid_remember_cookie?, and xml_not_supported"}
|
How to create a manual issue in sonarqube
|
On the profiles page, there's a down-arrow next to the 'Create' menu at the top of the column on the left. It offers two options:Restore Profile - restore a single, specific profile from a backup file that you'll uploadRestore Built-in Profiles - restore all default profiles for a single, specific language.You want the latter.
|
I'm using sonarqube and I've kind of messed up the rules inside the sonar way profile. Is there a way to put it back as it was before ? Like updating the java plugin. Because I don't find the list of rules inside the default "sonar way" profile on the sonarqube web site.Thanks.
|
Sonarqube, get back the original sonar way
|
You can't, not directly in Netbeans.SonarLintis available for IntelliJ IDEA, and Eclipse to run those rules locally, but not for NetBeans. You could, however, run aPreview analysis.
|
I would like do locally the code analysis that Sonar does on the server.Concerning the rules for PMD, Findbugs and Checkstyle I have no problems to download them and import in Netbeans with the appropriate plugins.My question concerns two additional sets of rules that I find in sonar called "JavaSonarQube"and "Java Common Sonarqube". At what kind of analyzer them refers to and how can I import and run them in NetBeans?
|
Analyzer for "JavaSonarQube" and "Java Common Sonarqube"
|
I think it might be a typo in the description, since S864 exists, and is about operator precedence. The link that you clicked on for finding S00864, update the URL to remove the 00 to just S864 to see the rule.
|
the rule Correctness - Integer multiply of result of integer remainder notes that "This rule is deprecated, use S00864 instead. ", but S00864 does not exist.
|
squid rule S00864 does not exist
|
This has nothing to do with the logger you use to log the issue. If you have a look at the updated description :http://jira.sonarsource.com/browse/RSPEC-1166// Noncompliant - exception is lost (only message is preserved)try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); }An issue is raised because you keep only the message of the exception and so you lose the information about the stacktrace which should be logged according to the rule.
|
When running SonarQube an exception is found called "Exception handlers should preserve the original exception". Full exception descriptionhere.The meaning is clear to us. The problem is that we are the following statement seems to be allowed by the compiler (see Compliant Solution):try { /* ... */ } catch (Exception e) { LOGGER.info("context", e); }We are not using LOGGER, but:trc.traceRaw(DcWxTaTrc.INFO, "Exception <" + e.getMessage() + ">
ignored");Is there a way to allow this kind of logging too? If yes: how?
|
Exception handlers should preserve the original exception
|
It's aknown limitationof this PMD rule and of the related Squid (SonarQube internal) rule. Feel free to vote for the resolution of this issue in next version of the Java plugin.
|
I have a class lets say BImpl which implement B interface and C abstract class. Both super classes have some method like doSomething() which implemented in abstract class C.interface B
{
Some doSomething();
}
abstract class C
{
protected Some doSomething()
{
//Do something here...
}
}And i implement BImpl as follows:class BImpl extends C implemensts B
{
public Some doSomething()
{
super.doSomething()
}
}So i expose abstract class behavior with B type object. With this scenario i get PMD (in sonar) violation that say "The overriding method merely calls the same method defined in a superclass ".
It quite not right to me because i expose other parent behavior. How can i avoid this?
|
Avoid The overriding method merely calls the same method defined in a superclass Sonar violation in multiple inheritance
|
http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.1Thelanguageattribute is deprecated.Use instead:<script type="text/javascript"></script>
|
In my project I am trying to resolve sonar violation, and I stuck with this one, I have following code<script language="JavaScript"......... > </script>the following attribute is not allowed : languageCan anybody tell me how to resolve this sonar violation ? Can I simply remove this "language"
attribute or should I put type="text/javascript" ?
|
Illegal attribute in jsp(sonar violation)
|
No. It's currently not possible.
|
I want to know if it is possible to export / import a dashboard configuration (widgets and their configuration) ?The aim of that is to save a dashboard before modify it or test a dashboard on a test instance of Sonar and import it when finished on the "production" instance of Sonar.Regards,Stéphane
|
Export and import dashboard in Sonar
|
If you're developing a .NET solution on Windows, chances are that your project is not encoding in UTF-8 but in cp-1252. Try with this encoding for "sonar.sourceEncoding".
|
When sonar scans my .net project, I get the following error messages. Where is the problem,thanksSonar version: 3.3.2sonar.sourceEncoding=UTF-817:24:08.040 WARN nownCharacterChannel - Unknown char: "" (file:/......../HtmlModule.ascx.cs:177:51)
17:24:08.040 WARN nownCharacterChannel - Unknown char: "" (file:/......../HtmlModule.ascx.cs:177:53)
17:24:08.040 WARN nownCharacterChannel - Unknown char: "" (file:/......../HtmlModule.ascx.cs:177:55)
17:24:08.040 WARN nownCharacterChannel - Unknown char: "" (file:/......../HtmlModule.ascx.cs:177:57)
17:24:08.040 WARN nownCharacterChannel - Unknown char: "" (file:/......../HtmlModule.ascx.cs:177:59)
17:24:08.040 WARN nownCharacterChannel - Unknown char: "" (file:/......../HtmlModule.ascx.cs:177:61)
17:24:08.041 WARN nownCharacterChannel - Unknown char: "" (file:/......../HtmlModule.ascx.cs:181:11)
17:24:08.041 WARN nownCharacterChannel - Unknown char: "" (file:/......../HtmlModule.ascx.cs:181:13)Source code;��using System;
using System.Data;
using System.Configuration;
using System.Collections;
......
|
Sonar Unknown char error for files with UTF-8
|
as requested, putting this as an answer:SONAR comes with an ANT taskAlso look atthis.
|
We build our projects with ant and happy with it.The other day, I wished to give Sonar a try only to discover that it requires me to have maven. So, I guess I need some kind of pom.xml somewhere in my project.There are three things I wish to avoid:Learn mavenright now(in general I may want to, but not now)Migrate to maven from antMaintain two build scripts - one for ant and the other for maven.Is it possible to have this pom.xml as minimal as possible and yet to be able to analyze the project with Sonar?Thanks.P.S.Less demanding Sonar alternatives are welcome as well.
|
How can I use Sonar with our project, which is built with ant?
|
Try deleting these 2 lines<Property Name="sonar.login">admin</Property>
<Property Name="sonar.password">sonar</Property>from yourSonarQube.Analysis.xmlfile.I was having the same problem and was able to resolve it by doing that. I think the issue is related to the scanner attempting to use login and password when they are present, but if the token is listed you should really just use that to authenticate.
|
I'm trying to setup a test environment to experiment with SonarQube. This are the steps I took so far:Downloaded and installed SonarQube. I am able to run it, navigate to http://localhost:9000Created a new project for a repo in Azure DevOps. Sonar is able to connect to it, read the repositories, etc.Donwloaded the latest version of SonarScanner.MsBuild runner. Unzipped and put the path into the %PATH% environment variableIn sonar I created a new User Token and put in theSonarQube.Analysis.xmlfrom the runner folder:<Property Name="sonar.host.url">http://localhost:9000</Property>
<Property Name="sonar.login">admin</Property>
<Property Name="sonar.password">sonar</Property>
<Property Name="sonar.token">squ_7b.......601</Property>Back to Sonar, I created a new local run.Selected the option toGenerate a project tokenand clicked NextThen Sonar is asking me to run the following command:SonarScanner.MSBuild.exe begin /k:"TEST_PROJECT-local" /d:sonar.host.url="http://localhost:9000" /d:sonar.token="sqp_ec60....a7e1"I can see the project token was create by Sonar. But when I run it, I get the following error:SonarScanner for MSBuild 5.13
Using the .NET Framework version of the Scanner for MSBuild
Pre-processing started.
Preparing working directories...
09:15:30.629 Updating build integration targets...
09:15:30.797 Unauthorized: Access is denied due to invalid credentials. Please check the authentication parameters.
09:15:30.8 Pre-processing failed. Exit code: 1What am I missing?
|
Unauthorized: Access is denied due to invalid credentials. Please check the authentication parameters in SonarQube SonarScanner.MsBuild.exe
|
Here's a logical reason for you:Thread.sleep(2000);will block the current thread for at least 2 seconds.By contrast:await().atMost(2, Duration.SECONDS).until(didTheThing());or equivalent code will block the current thread for up to 2 seconds, and will stop waiting when the event occurs.The latter is more responsive.The only situation wheresleep()might be preferable are where the thread is not waiting for an event related to another Java thread. Even then,sleepmay end up waiting longer than you asked for, so it is not suitable for "real time" timing.This specific warning is in the context of test code, but the advice against usingsleep()applies more generally.I've never come acrossAwaitilitybefore, but it seems like it is designed to make it easier to write unit tests that entail timing checks. In the example in questions ... it appears that it would have the benefit of making your tests run faster!And as a commenter pointed out, thedocumentationfor the rule explains the reasoning itself:Thread.sleepshould not be used in testsUsingThread.sleepin a test is just generally a bad idea. It creates brittle tests that can fail unpredictably depending on environment ("Passes on my machine!") or load. Don't rely on timing. Use mocks or use libraries such asAwaitilityfor asynchronous testing.
|
According to this document (rule) S2925https://rules.sonarsource.com/java/RSPEC-2925We need to change theThread.sleepwith:await().atMost(2, Duration.SECONDS).until(didTheThing())Can someone give me any logical answer why we need to do that?When thisAwaitilityclass creates thread in the backend. What is the point of this rule?
|
Why does Sonar recommend avoiding Thread.sleep?
|
Each time you invoke a method, you might get back a different result. You may know that you will get the same result back each time, but Sonarqube doesn't.Assignresponse.getBody()to a variable so you don't have to call it again:if (response != null) {
var body = response.getBody();
if (body != null) {
return body.getData();
}
}
return null;You can do it with Optional, alternatively:return Optional.ofNullable(response).map(ResponseType::getBody).map(BodyType::getData).orElse(null);
|
I'm finding a problem in my Sonar I don't know how to solve.The error I have is:Possible null pointer dereference in mypackage.myMethod(String) due to return value of called methodAt the very begining it was:response.getBody().getData();So what I did was:return (response != null && response.getBody() != null) ? response.getBody().getData() : null;But the error is still there.Am I missunderstanding the error?? How can I solve?
|
sonar rule "possible null pointer exception"
|
Have you tried using sonar.exclusions in your POM properties?<properties>
<sonar.exclusions>
**/model/*.java
</sonar.exclusions>
</properties>
|
I have a package,com.org.projectname.model, in my project. What I want to do is exclude all the files within this package from SonarQube coverage. I tried,<exclude>**/model /*.class</exclude>and<exclude>**/com/org/projectname/model/*.class</exclude>, but this didn't work.<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.6</version>
<configuration>
<excludes>
</excludes>
</configuration>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<destFile>target/coverage-data/jacoco-ut.exec</destFile>
<propertyName>surefireArgLine</propertyName>
</configuration>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>target/coverage-data/jacoco-ut.exec</dataFile>
<outputDirectory>target/coverage-reports/jacoco-ut</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>How to fix this issue? Or is there any other way?
|
Exclude files/packages from SonarQube coverage
|
I added validation for the Location variable and this solved the issueif(!location.matches(...)) {
throw error.....
}
String url = apiUrl + location;
|
I facing a SonarQube bug and am not able to figure out whats the issue. SonnarQube's issue is, change this code to not construct the URL from user-controlled data.@Value("${...}")
String apiKey;
@Value("${...}")
String apiUrl;
public Response apiResponse(String location) {
HttpHeaders headers = new HttpHeaders();
headers.add("x-apikey", apiKey);
HttpEntity<Object> entity = new HttpEntity<>(headers);
String url = apiUrl + location; // SonarQube issue: tainted value is propagated
Response response = null;
try {
ResponseEntity<Response> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Response.class); // SonarQube issue: Tainted value is used to perform a security- sensitive operation.
response = responseEntity.getBody();
} catch(Exception){
// doesn't throw anything
}
return response;
}
@Cacheable(...)
Response cacheResponse(String location, String tokenKey) {
return apiResponse(location); // SonarQube issue: tainted value is propagated
}This fixed the issue, but why is that so? and how can I apply this in the above code?String url = apiUrl + location; // SonarQube issue: taintedInstead, I just tried hardcoding the value of location and fixed the issue.String url = apiUrl + "location";So weird...
|
SonnarQube's issue: change code to not construct the URL from user-controlled data
|
You may rewrite it as:useEffect(() => {
if (isFocused) {
if (isLoggedIn) getProfileData();
dispatch(rewardsLandingScreenTracker());
}
}, [dispatch, getProfileData, isLoggedIn, isFocused]);oruseEffect(() => {
if (!isFocused) return
if (isLoggedIn) getProfileData();
dispatch(rewardsLandingScreenTracker());
}, [dispatch, getProfileData, isLoggedIn, isFocused]);The second one may raise lint error on inconsistent return (depends on your linter settings). Then you'll have to add explicitreturnat the end of the callback function.
|
I'm getting error in sonar for cognitive complexity, find my code and attached screenshot for more reference. Please help me to resolve thisuseEffect(() => {
if (isFocused && isLoggedIn) {
getProfileData();
}
if (isFocused) {
dispatch(rewardsLandingScreenTracker());
}
}, [dispatch, getProfileData, isLoggedIn, isFocused]);Can someone also update me what will be the solution in case of ternary operator likeconst savedPrice =
(actualPrice ? getConvertedPrice(actualPrice) : 0) -
(proPrice ? getConvertedPrice(proPrice) : 0);
|
Refactor this function to reduce its Cognitive Complexity for if else condition
|
The reason for this was that the Personal Access Token used had expired, or at least creating a new one fixed this.So go tohttps://sonarcloud.io/project/settings?category=pull_request&id=*projectkey* and change the Personal access token and queue the build.
|
We have a Sonarcloud quality gate in the Pull request policy in Azure Devops. Mostly it works but sometimes it get's stuck. We added an update to the PR but is it still at status Waiting in Azure Devops. When I check Sonarcloud for this branch it says Passed.How can I restart the gate or can I debug Sonarcloud if that e.g. has taken longer that what Azure Devops is waiting?
|
Sonarcloud gate in Azure Devops pull request stuck in waiting status
|
Whatmapdoes is does transformation in its callback and returns the new transformed array as a new reference (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). The returned new transformed array is not being used and therefore Sonar is saying to change it to aforEach.Changing it tocontext.keys().forEach(context);runs the unit tests for me and everything is fine however Angular CLI has it asmapso I am going to keep it asmap.
|
I started my angular project on sonar and for the test.ts sonar file I get an error for the following line:context.keys().map(context);Consider using "forEach" instead of "map" as its return value is not being used hereI don't understand why
|
Error when using instruction map in angular
|
You have missed to add two mandatory sonar analysis properties.Those two are:-Dsonar.sources=srcand-Dsonar.java.binaries=**/*You can mention both the properties in the Jenkins step likesh "sonar-scanner -Dproject.settings=../sonar-project.properties -Dsonar.version=${params.buildVersion} -Dsonar.projectVersion=${params.projectVersion} -Dsonar.sources=src -Dsonar.java.binaries=**/*"OrYou can include them insonar-project.propertieslikesonar.sourceEncoding=UTF-8
sonar.projectKey=com.company.project:parent
sonar.sources=src
sonar.java.binaries=**/*
#List of module identifiers
sonar.modules=../module1,../module2,../module3
#module1 settings
module1.sonar.projectName=com.company.project:module1
module1.sonar.sources=src/main/java
#module2 settings
module2.sonar.projectName=com.company.project:module2
module2.sonar.sources=src/main/java
#module3 settings
module3.sonar.projectName=com.company.project:module3
module3.sonar.sources=src/main/javaNote:sonar.java.binariesis important for analysis of maven projects.
|
I have the following structure for a maven project:sonar-project.properties
Jenkinsfile
parent
->parent
->->pom.xml
->module1
->->pom.xml
->module2
->->pom.xml
->module3
->->pom.xmlpom parent:<modules>
<module>../module1</module>
<module>../module2</module>
<module>../module3</module>
</modules>sonar-project.properties :sonar.sourceEncoding=UTF-8
sonar.projectKey=com.company.project:parent
#List of module identifiers
sonar.modules=../module1,../module2,../module3
#module1 settings
module1.sonar.projectName=com.company.project:module1
module1.sonar.sources=src/main/java
#module2 settings
module2.sonar.projectName=com.company.project:module2
module2.sonar.sources=src/main/java
#module3 settings
module3.sonar.projectName=com.company.project:module3
module3.sonar.sources=src/main/javaMy Jenkins pipeline is :steps {
script {
dir('parent') {
withSonarQubeEnv('SONAR') {
sh "sonar-scanner -Dproject.settings=../sonar-project.properties -Dsonar.version=${params.buildVersion} -Dsonar.projectVersion=${params.projectVersion}"
}
}
}
}I have this error:ERROR: You must define the following mandatory properties for 'com.company.project:parent:../module1': sonar.sources
|
SonarQube multi module maven project
|
Request Entity Too LargeI got this when I was using the Nginx server for SonarQube.ExplanationA 413 HTTP error code occurs when the size of a client's request exceeds the server's file size limit. This typically happens when a client attempts to upload a large file to a web server, and the server responds with a 413 error to alert the client.SolutionFor Nginx serversTo allow the request size to be up to 20 megabytes, add the following line to your Nginx configuration file:...
client_max_body_size 20M;
....configuration files should be found in/etc/nginx/directoryTipsI would recommend updating the dedicated configuration file for SonarQube server placed inside/etc/nginx/sites-enabled/folderthis property can be placed inside theserver {...},http {...}or,location{...}block of the configuration file
|
I am running sonarqube using gradle command ./gradlew sonarqube -Dsonar.host.url=https://sonar-server-url.
I am getting error Failed to upload report - HTTP code 413.
Request Entity Too Large.
I am using sonarserver version : Community Edition Version 7.8.
I am running sonar report using gradle command: ./gradlew sonarqube -Dsonar.host.url=https://sonar-server-url
I am getting error Failed to upload report.
Sonarqube server is on oracle cloud (oci) node and the report file size is 10M.
|
Sonarqube Failed to upload report 413
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.