Why does Sonarqube mark try as a critical issue? - maven

I'm currently facing an issue with some SonarQube's analysis being performed over some Kotlin code I wrote.
I'm trying to implement a method that connects to the database and returns accordingly to the query's result. I'm not sure how related this can be, but I added the following maven dependencies to my project:
Quarkus
Arrow
Ktorm
The code is the following:
#ApplicationScoped
class Repository(private val database: Database) {
override fun get(name: String): Either<Error, Brand> =
try {
database.brands.find { it.name eq name }.rightIfNotNull {
MissingBrandError("Missing brand")
}
} catch (e: Exception) {
Either.Left(DatabaseError(e.message))
}
}
class Error(val message: String)
class MissingUserError(val message: String) : Error(message)
class DatabaseError(val message: String? = null) : Error(message ?: "Some database error")
NOTE: Database object is of type org.ktorm.database.Database and brands is of type org.ktorm.entity.EntitySequence
The code is working and I also wrote unit tests for it that pass and give enough coverage (accordingly to the code coverage analysis tool), but at some point in my pipeline SonarQube marks the try as a critical issue with the following message:
Possible null pointer dereference in (...)Repository(String) due to return value of called method
I checked it online and I could find some related questions, but none of the provided answers worked for me. Amongst the many attempts these are the ones I can remember I tried without any success:
Not inlining any code (pretty much using Java style code)
Extracting the query result to a variable
Check with if/else statements for nullability instead (both with inlined try and without)
I'd also like to highlight that all I can see on Sonar is the generated report and CLI for the running build. I don't have access to any of its configuration or intended to change them (unless of course it comes down to that). The line I mentioned seems to be the only one affected by this problem according to Sonar's report, that's why this is the solo class I provided.
I hope I provided enough info and that any of you can help me with this. Thanks in advance.

Related

How to ignore failure/skipping statement in cucumber for next than statements

In cucumber suppose my one than statement is failed then my all than statement is skipped by cucumber for that scenario and it started executing next scenario ... Do anyone have any way to assist cucumber to run next step without skipping all other than statement for that scenario.. do we have any provision for same?
I am using cucumber, maven with java
This is a bad practice. If you have the need for something like this, it only means that your Cucumber scenario is not written properly.
Having said that, if there is a step that is expected to fail but its failure does not imply a failure of the whole scenario, you will have to implement some sort of "failsafe" workaround within your glue code. For example try...catch clause that will acknowledge the failure, perhaps log it but will not fail the scenario due to thrown exception.
Cucumber steps should not be polluted with internal logic.
If a step in a scenario fails, then the entire scenario fails. To do anything else undermines several principles of testing. Once a failure has happened executing the subsequent steps make no sense as we don't have a consistent starting point ( something has already gone wrong)
If you want to run a single scenario and exclude a particular step, just remove it from the scenario.
In this case its up to you to use the tool properly. Cucumber is not going to help you do stupid things with it.
You can either handle it using try - - - catch block or you can use soft assertion
Soft Assertions are the type of assertions that do not throw an exception when an assertion fails and would continue with the next step after assert statement.This is usually used when our test requires multiple assertions to be executed and the user want all of the assertions/codes to be executed before failing/skipping the tests.AssertJ is library providing fluent assertions. It is very similar to Hamcrest which comes by default with JUnit. Along with all the asserts AssertJ provides soft assertions with its SoftAssertions class inside org.assertj.core.api package
Consider the below example:
public class Sample {
#Test
public void test1() {
SoftAssert sa = new SoftAssert();
sa.assertTrue(2 < 1);
System.out.println(“Assertion Failed”);
sa.assertFalse(1 < 2);
System.out.println(“Assertion Failed”);
sa.assertEquals(“Sample”, “Failed”);
System.out.println(“Assertion Failed”);
}
}
Output:
Assertion Failed Assertion Failed Assertion Failed
PASSED: test1
Even now the test PASSED instead of FAILED. The problem here is the test would not fail when an exception is not thrown. In order to achieve the desired result we need to call the assertAll() method at the end of the test which will collate all the exceptions thrown and fail the test if necessary.
Extending the SachinB answer.
We can use assertj to achive same.
We need to use it's lib/dependency as below
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.9.0</version>
</dependency>
You need to create object of SoftAssertions() which is provide by assetj
package you need to import
import org.assertj.core.api.SoftAssertions;
Example code
public class myclass {
SoftAssertions sa = null;
#Then("^mycucucmberquote$")
public void testCase2() {
sa = new SoftAssertions();
sa.assertThat("a").contains("b");
}
#Then("^mycucucmberquoteLastThen of that scario$")
public void testCase3() {
try {
sa.assertAll();
} catch (Exception e) {
}
}
}
sa.assertAll(); implemented function fails and it will provide the stack trace of failed steps.

Xcode UI Testing: Automatically taking snapshot when predicates fail?

Xcode UI Testing takes automatic screenshots for viewing in the results navigator whenever a test fails, which is greatly helpful. However, that does not include tests that fail because a predicate is failed. Since predicates are often for basic checks (such as if an element exists or not on a current view), that is a huge drawback because a screenshot would be useful in diagnosing what was happening in the app when the test failed.
Does anyone know how to force a screenshot? Does this require integrating the Fastlane Snapshot tool?
On tearDown you can check if test failed (that's helpful if you are not discarding screenshots when tests pass.)
if let failureCount = testRun?.failureCount, failureCount > 0 {
takeScreenshot()
}
If you are using Xcode 9 already, the takeScreenshot function can use the new API (If not, then use the workaround mentioned by the other answer) :
let screenshot = XCUIScreen.main.screenshot()
let attach = XCTAttachment(screenshot: screenshot)
add(attach)
You can also name the attach and change its lifetime ;)
See Apple's documentation for how to use and where to find them (the "Report navigator" in View > Navigators > Reports) in more detail.
You don't have to integrate Fastlane Snapshot for this. The only trick Snapshot is doing to force screenshot is triggering this code:
XCUIDevice.shared().orientation = .unknown
This will not alter UI as described on Snapshot documentation.
Unfortunately this will not work if you're using expectation for your predicate and you put this code into waitForExpectations(timeout:handler:) handler closure and I don't know why.
To workaround this you can create your own XCTestObservation handler like this:
class MockObserver: NSObject, XCTestObservation {
func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: UInt) {
XCUIDevice.shared().orientation = .unknown
}
}
XCTestObservationCenter.shared().addTestObserver(MockObserver())
You can put this code in either setUp() method or specific test... method.
The test output is a little weird as it will show "Set device orientation to Unknown" as an error and actual predicate error inside but you will have your screenshot:
You can override the recordFailure method to capture screenshots on any kinds of failures.
override func recordFailure(withDescription description: String, inFile filePath: String, atLine lineNumber: Int, expected: Bool) {
add(XCTAttachment(screenshot: XCUIScreen.main.screenshot()))
super.recordFailure(withDescription: description, inFile: filePath, atLine: lineNumber, expected: expected)
}

AX2012 - Pre-Processed RecId parameter not found

I made a custom report in AX2012, to replace the WHS Shipping pick list. The custom report is RDP based. I have no trouble running it directly (with the parameters dialog), but when I try to use the controller (WHSPickListShippingController), I get an error saying "Pre-Processed RecId not found. Cannot process report. Indicates a development error."
The error is because in the class SrsReportProviderQueryBuilder (setArgs method), the map variable reportProviderParameters is empty. I have no idea why that is. The code in my Data provider runs okay. Here is my code for running the report :
WHSWorkId id = 'LAM-000052';
WHSPickListShippingController controller;
Args args;
WHSShipmentTable whsShipmentTable;
WHSWorkTable whsWorkTable;
clWHSPickListShippingContract contract; //My custom RDP Contract
whsShipmentTable = WHSShipmentTable::find(whsWorkTable.ShipmentId);
args = new Args(ssrsReportStr(WHSPickListShipping, Report));
args.record(whsShipmentTable);
args.parm(whsShipmentTable.LoadId);
contract = new clWHSPickListShippingContract();
controller = new WHSPickListShippingController();
controller.parmReportName(ssrsReportStr(WHSPickListShipping, Report));
controller.parmShowDialog(false);
controller.parmLoadFromSysLastValue(false);
controller.parmReportContract().parmRdpContract(contract);
controller.parmReportContract().parmRdpName(classStr(clWHSPickListShippingDP));
controller.parmReportContract().parmRdlContract().parmLanguageId(CompanyInfo::languageId());
controller.parmArgs(args);
controller.startOperation();
I don't know if I'm clear enough... But I've been looking for a fix for hours without success, so I thought I'd ask here. Is there a reason why this variable (which comes from the method parameter AifQueryBuilderArgs) would be empty?
I'm thinking your issue is with these lines (try removing):
controller.parmReportContract().parmRdpContract(contract);
controller.parmReportContract().parmRdpName(classStr(clWHSPickListShippingDP));
controller.parmReportContract().parmRdlContract().parmLanguageId(CompanyInfo::languageId());
The style I'd expect to see with your contract would be like this:
controller = new WHSPickListShippingController();
contract = controller.getDataContractObject();
contract.parmWhatever('ParametersHere');
controller.parmArgs(args);
And for the DataProvider clWHSPickListShippingDP, usually if a report is using a DataProvider, you don't manually set it, but the DP extends SRSReportDataProviderBase and has an attribute SRSReportParameterAttribute(...) decorating the class declaration in this style:
[SRSReportParameterAttribute(classstr(MyCustomContract))]
class MyCustomDP extends SRSReportDataProviderBase
{
// Vars
}
You are using controller.parmReportContract().parmRdpContract(contract); wrong, as this is more for run-time modifications. It's typically used for accessing the contract for preRunModifyContract overloads.
Build your CrossReference in a development environment then right click on \Classes\SrsReportDataContract\parmRdpContract and click Add-Ins>Cross-reference>Used By to see how that is generally used.
Ok, so now I feel very stupid for spending so much time on that error, when it's such a tiny thing...
The erronous line is that one :
controller.parmReportName(ssrsReportStr(WHSPickListShipping, Report));
Because WHSPickListShipping is the name of the AX report, but I renamed my custom report clWHSPickListShipping. What confused me was that my DataProvider class was executing as wanted.

Findbugs validation in SONAR are skipping important violations

I'm having a problem with violation in Sonar to find a basic problem in some codes that we have in my company. Below there is a test class that represents the situation that I want to clarify:
import entity.Cidade;
public class TesteSonar {
public void testarSonar() {
Cidade cidade = testarSonar2();
cidade.getEstado();
}
public Cidade testarSonar2() {
return null;
}
}
In this class, we have the situation where the variable "cidade" receives the return of the method "testarSonar2()" that is null, and after that I use a action from this object. It's obvious that will throw a NullPointerException. My question is: Why findbugs didn't catch this kind of problem?
This situation points to a credibility problem in Sonar in the results that I receive from the tool. Could anyone help to understand why this is happing this way?
Thank's
Alexandre from Brazil
I've just made a test and indeed, no error is reported.
However, please note that the problem comes from Findbugs, not from Sonar itself - as Sonar relies on external tools for bug detection. So I'd advise you to ask the question on the Findbugs' mailing list.

What are your favorite Grails debugging tricks? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Grails can be a bit of a bear to debug with its long stack dumps. Getting to the source of the problem can be tricky. I've gotten burned a few times in the BootStrap.groovy doing "def foo = new Foo(a: a, b: b).save()", for example. What are your favorite tricks for debugging Grails apps?
Some general tips:
Clear stacktrace.log, do grails run-app, then open stacktrace.log in a viewer (I prefer less stacktrace.log on linux)... once in your viewer, search for .groovy and .gsp... that generally brings you to what you actually care about.
When a stacktrace refers to a line number in a GSP file, you should open that view in a browser with ?showSource in the query string, i.e. http://localhost:8080/myProject/myController/myAction?showSource... this shows the compiled GSP source, and all GSP line numbers in the stacktrace refer to the compiled GSP, not the actual GSP source
Always, always, always surround your saves with at least some minimal error handling.
Example:
try {
if(!someDomainObject.save()) {
throw new Exception ("Save failed")
}
} catch(Exception e) {
println e.toString()
// This will at least tell you what is wrong with
// the instance you are trying to save
someDomainObject.errors.allErrors.each {error ->
println error.toString()
}
}
Beyond that, a lot of it just comes down to recognizing stacktraces and error messages... a lot of the time, Grails is incredibly unhelpful in the error messages it gives you, but you can learn to recognize patterns, like the following:
Some of the hardest errors to make sense of are because you didn't run grails clean or grails upgrade... to avoid these problems, I always use the following on the command line to run grails: grails clean; yes | grails upgrade; grails run-app
If the error has to do with duplicate definitions of a class, make sure that you declare the package the class belongs to at the top of the class's file
If the error has to do with schema metadata, connection, socket, or anything like that, make sure your database connector is in lib/, make sure your permissions are correct both in DataSource.groovy and in the database for username, password, and host, and make sure that you know the ins and outs of your connector's version (i.e. mysql connector version 5.1.X has a weird issue with aliases that may require you to set useOldAliasMetadataBehavior=true on the url in DataSource.groovy)
And so on. There are a lot of patterns to learn to recognize.
To add to Chris King's suggestion on save, I wrote a reusable closure:
Closure saveClosure = { domainObj ->
if(domainObj.save())
println "Domain Object $domainObj Saved"
else
{
println "Errors Found During Save of $domainObj!"
println domainObj.errors.allErrors.each {
println it.defaultMessage
}
}
}
Then you can just use it everywhere and it will take care of error reporting:
def book = new Book(authorName:"Mark Twain")
saveClosure(book)
Additionally, I use the debug plugin - it allows extra logging, and I added tag to the bottom of my main - that gives me a view of all the variables in session / request.
Runtime Logging plugin allows to enable logging at runtime.
While writing this answer, P6SPY plugin also seems like it could be useful - it logs all statements your app makes against the database by acting as a proxy.
Grails Console is also useful. I use it to interactively poke around and experiment with some code, which also comes in handy during debugging.
And of course, being able to step through Debugger is sweet. I switched to IntelliJ IDEA since it has the best Grails / Groovy support.
I once asked an experienced groovy developer about how he effectively debugged his applications. His answer:
I write tests!
And he has a very good point: If your code has sufficient unit and integration tests, you will hardly ever need to debug anything. Plus you get to say smug things like that to your fellow developers...
For Grails:
Unit Testing
Functional Testing
Really excellent grails app testing developerWorks article
To log exceptions with GrailsUtil.
try{
...
}catch (Exception e){
log.error("some message", GrailsUtil.sanitize(e))
...
}
More info about sanitize.
I'm not sure if this can be done out-of-the-box, but in webapps I find it useful to have a "who am I?" facility in the various view files.
The idea is to emit a message into the rendered HTML, to identify the fragment. This is especially true when I am encountering an app for the first time.
In Grails, I do this with a custom tag. For example, consider list.gsp for a Student:
<g:debug msg="student list" />
Here is the code:
class MiscTagLib {
def debug = { map ->
if (grailsApplication.config.grails.views.debug.mode == true) {
def msg = map['msg']
out << "<h2>${msg}</h2><br/>"
}
}
}
The key is that you can leave those tags in there, if desired, as they only appear in when the mode is enabled in Config.groovy:
grails.views.debug.mode=true
adding this code To the Bootsrap.groovy:init will overwrite the save method and execute some other code as well, printing out error messages in this case.
class BootStrap {
def grailsApplication
def init = {servletContext ->
grailsApplication.domainClasses.each { clazz ->
clazz.clazz.get(-1)
def gormSave = clazz.metaClass.getMetaMethod('save')
clazz.metaClass.save = {->
def savedInstance = gormSave.invoke(delegate)
if (!savedInstance) {
delegate.errors.each {
println it
}
}
savedInstance
}
def gormSaveMap = clazz.metaClass.getMetaMethod('save', Map)
clazz.metaClass.save = { Map m ->
def savedInstance = gormSaveMap.invoke(delegate, m)
if (!savedInstance) {
delegate.errors.each {
println it
}
}
savedInstance
}
def gormSaveBoolean = clazz.metaClass.getMetaMethod('save', Boolean)
clazz.metaClass.save = { Boolean b ->
def savedInstance = gormSaveBoolean.invoke(delegate, b)
if (!savedInstance) {
delegate.errors.each {
println it
}
}
savedInstance
}
}
...
}
hope that helps someone :)
(i know its not really DRY)
ref: http://grails.1312388.n4.nabble.com/How-to-override-save-method-on-domain-class-td3021424.html
Looking at the source code! This has saved me so many times now! And now that the code is hosted at GitHub it's easier than ever. Just press "t" and start typing to find the class that you're looking for!
http://github.com/grails/grails-core
Here's some tricks collected by #groovymag from Grails people in twitter:
http://blog.groovymag.com/2009/02/groovygrails-debugging/
For simple applications I use println statement.It is very very easy trick.For complex applications use debug mode in intellij idea.

Resources