I was working on injecting of groovy scripts dynamically in Java. So before executing those scripts, I want to get sure of that they do not have potential bugs using SpotBugs (static code analyzer). Here is the Psuedo-Code:
Here it should return the infinite loop bug.
String script = "class Hello { static void main(String []args) { def i = 0; while ( i <= 0) { i = i - 1; } } } ";
List<Bugs> bugs = SpotBugs.getBugs(script);
if (bugs == null) {
execute(script);
}
So how to do the SpotBugs.getBugs(script)
using java, the input script will not be hard-coded as in above example, but will be dynamically fetched.
The easiest way is to write the compiled code to class files (in a temp directory if needed). By having compiled class as file, you will be able to use the FindBugs
class which provide an API to configure the scope and rules without playing with internal classes that are subject to changes.
However, the main obstacle you'll face is that groovy bytecode is too obfuscated for SpotBugs. For the call to function abc()
, you will not see an invoke to method abc
in the bytecode. It will be a reference to a global functions map that is created at runtime. Groovy has a mode to compile to a less dynamic format. This mode does not allow functions to be created at runtime. You can check the configuration to instruct the compiler for the static mode in this test repo: https://github.com/find-sec-bugs/find-sec-bugs-demos/tree/master/groovy-simple. This is, however, a Gradle compilation not a programmatic API that received a String as code.