How to fix RuntimeException: error reading Scala signature of com.snp.utils.DbUtils: error reading Scala signature - scala

I have defined
var status:String = null;
var error_msg:String = null;
try{ status ="Error"; error_msg= "n/a";
}
When I place my method in DbUtils object and call from my main class it is throwing error, i.e. when calling
DbUtils.writeToCassandraAuditLog(spark, status, error_msg);
it throws below error
2018-10-23 14:03:37 ERROR java.lang.RuntimeException: error reading Scala signature of com.snp.utils.DbUtils: error reading Scala signature of org.apache.spark.sql.package: assertion failed: unsafe symbol Unstable (child of <none>) in runtime reflection universe
at scala.reflect.internal.pickling.UnPickler.unpickle(UnPickler.scala:46)
But when I place/define the methods in my main class/object it is working fine.
writeToCassandraAuditLog(spark, status, error_msg);
How to fix this issue?

Related

how to mock a method that throws an exception

The following method throws an exception if a question is not found
def getQuestionFromQuestionID(questionKey: PracticeQuestionKeys) = {
logger.trace(s"getting question with keys ${questionKey}")
val practiceQuestionFuture: Future[Option[PracticeQuestion]] = findOne(questionKey)
for (questionOption <- practiceQuestionFuture) yield {
questionOption.fold(throw QuestionNotFoundException())(question => {
logger.trace("got question " + question)
question
})
}
}
I call it like the following in a controller.
def function1(){...
val res = for{existingQuestion <- questionsRepository.getQuestionFromQuestionID(questionKey)
res.recover{
case exception =>...
}...}
...}
I am writing a test for function1 simulating that an exception is thrown. I wrote the following but I get dead code error when I compile the code.
when(answerTestEnv.mockPracticeQuestionsRepository.getQuestionFromQuestionID(ArgumentMatchers.any[PracticeQuestionKeys])).thenReturn(
throw QuestionNotFoundException()
)
Error
Error:(92, 9) dead code following this construct
throw QuestionNotFoundException()
I changed the code to
when(answerTestEnv.mockPracticeQuestionsRepository.getQuestionFromQuestionID(ArgumentMatchers.any[PracticeQuestionKeys])).thenThrow(
QuestionNotFoundException()
)
But the test case fails with error
Checked exception is invalid for this method!
Invalid: utilities.QuestionNotFoundException: Question not found
org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: utilities.QuestionNotFoundException: Question not found
How can I simulate the exception scenario?
For methods with return value you can use .thenThrow (I's assuming you are using mockito, because scalamock uses different conventions)
when(
answerTestEnv
.mockPracticeQuestionsRepository
.getQuestionFromQuestionID(ArgumentMatchers.any[PracticeQuestionKeys])
).thenThrow(new QuestionNotFoundException())
and if the method is of type void (Unit) you use doThrow(ex).when(mock).call:
doThrow(new QuestionNotFoundException())
.when(answerTestEnv.mockPracticeQuestionsRepository)
.getQuestionFromQuestionID(ArgumentMatchers.any[PracticeQuestionKeys])

Generics: Type argument is not within its bounds

Any idea why the following code wouldn't compile?
fun <T : Comparable<T>> naturalSort(list: List<T>): List<T> {
val natComparator = naturalOrder<T>() // compiler error here
return list.sortedWith(natComparator)
}
The second line results in the compiler error:
Type argument is not within its bounds: should be subtype of 'Comparable'
Update:
It works for me in https://play.kotlinlang.org/ but fails in Eclipse and when building the project (from Eclipse) with the project's Gradle build script.
Here's how my Gradle build environment looks like:
https://pastebin.com/0GDUWy2C
Solved. The problem was caused by the wrong Comparable interface being used due to import statements in the actual code (no problem with the import statements, not really sure why java.lang.Comparable was used instead of kotlin.Comparable). Specifying in the code that kotlin.Comparable should be used resolves the issue:
fun <T : kotlin.Comparable<T>> naturalSort(list: List<T>): List<T> {
val natComparator = naturalOrder<T>() // no error
return list.sortedWith(natComparator)
}
Thanks to everyone who responded.

Drools Error : Unable to find #positional field

I created a drool file PersonTotalAccountsBalance.drl as below. I am beginner in the rules engine world.
package com.auhuman.rules;
import com.auhuman.Person;
import com.auhuman.Account;
function float getTotalBalance(Person person) {
float totalBalance = 0;
for (Account account : person.getAccounts()){
totalBalance += account.getBalance();
}
return totalBalance;
}
rule "PersonTotalAccountsBalance"
when
$node : Person(active == true)
then
float totalBalance = getTotalBalance($node)
modify($node) {
setTotalBalance(totalBalance);
}
end
Upon compile I am getting below error
Unable to compile the file: PersonTotalAccountsBalance.drl. Errors = [Unable to find #positional field 0 for class Person
: [Rule name='PersonTotalAccountsBalance']
]
Although this question is very old:
I had the same error message but I was working with decision tables in xls (excel) format. The table looked like this:
Note that $order:Order is in a merged cell goes across both the CONDITION and the ACTION columns. That cell is only allowed to be above CONDITION tables, not the ACTION tables. After unmerging I didn't get the error anymore:
I got a very similar error when defining the wrong values in the ACTION column for setting an attribute. When using values without quotes for a String attribute in the model Order I got the following error:
Unable to get KieModule, Errors Existed: Error Messages:
Message [id=1, kieBase=defaultKieBase, level=ERROR, path=status_rules/status.xls, line=21, column=0
text=Rule Compilation error The method setNextStatus(String) in the type Order is not applicable for the arguments (int)]
Message [id=2, kieBase=defaultKieBase, level=ERROR, path=status_rules/status.xls, line=5, column=0
text=Rule Compilation error The method setNextStatus(String) in the type Order is not applicable for the arguments (int)]
Message [id=3, kieBase=defaultKieBase, level=ERROR, path=status_rules/status.xls, line=13, column=0
text=Rule Compilation error The method setNextStatus(String) in the type Order is not applicable for the arguments (int)]
However in this case the error message was more precise.

Compiler error while converting java Exception code to scala using intercept : ''forward reference extends over definition of value exception'

How to convert exception catching code from java to scala using intercept ?
From reading http://www.scalatest.org/getting_started_with_fun_suite it seems to be recommended to use intercept when catching exceptions. In the exception catching code below I need to access the Exception type so as to check its type within the
assert :
catch {
case me : MyException => {
assert(me.getDetail.getClass() === classOf[GenericException]);
}
}
This does not seem to be possible using intercept as below code causes a compiler error : 'forward reference extends over definition of value exception'
Here is the converted to scala catch block :
val exception = intercept[MyException] {
assert(exception.getDetail.getClass() === classOf[GenericException]);
}
The error occurs on line
assert(exception.getDetail.getClass() === classOf[GenericException]);
Well your definition of exception is circular. What you want is:
val exception = intercept[MyException] {
<your exception-throwing code here>
}
assert(exception.getDetail.getClass() === classOf[GenericException])

Early return from a Scala constructor

I am writing the constructor for my "main" class. The first thing it does is call a method to use commons-cli to parse the command line. If the parseOptions method returns false, an error has occurred, and the constructor should exit.
I tried writing the following code
if (!parseOptions(args)) return
but the compiler complains that I have a "Return statement outside method definition".
Short of calling System.exit(1) or inverting the boolean (and putting all of the rest of my logic inside the if statement, is there any way to return "early" from a constructor?
I suppose I could have the parseOptions method throw an IllegalArgumentException and catch that in my Main object.
Thanks.
Dont try to do a early/premature return, this makes your code harder more complex, since the side effects of the return can be hard to understand. Instead use a exception to signal that something is wrong.
You can use require in the constructor. This doesn't return. But it seems like throwing an exception actually fits his situation better.
As in:
class MyTest(
private var myValue: Int ){
require(myValue > 0) // Connected to constructor
}
defined class MyTest
scala> val x = new MyTest(10)
x: MyTest = MyTest#49ff4282
scala> val y = new MyTest(-10)
java.lang.IllegalArgumentException: requirement failed
at scala.Predef$.require(Predef.scala:133)
is there any way to return "early" from a constructor
No. But in your case it sounds like bad design, anyway.
If the parseOptions method returns false, an error has occurred
In this case the constructor should throw an exception, not return normally.
A constructor should always either complete fully, or abort (throw an exception). Anything else leaves your object "half constructed" and thus impossible to reason about.
If in your case, the object is valid even if parseOptions failed, then you can change the condition and continue:
if (parseOptions(args)) {
// rest of constructor
}