Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy can i dynamically execute a string as groovy command?

I would like to dynamically execute a groovy statement from my database.

I'm currently using geb (www.gebish.org) to automate my browser and i would like the use "css selectors" from my database.

For example:

Browser.drive {
   go "www.test.com"

   $("form", name: "password").value("Test")
}

In this example i would like to move "$("form", name: "password").value("Test")" completely to the database and just call it dynamically in my code. In such a thing possible?

I'm new to Groovy and Java and maybe i have a error in reasoning and there is a simpler solution for such a problem...please help me :)

like image 260
lawiet Avatar asked Dec 06 '22 20:12

lawiet


2 Answers

If you have some Groovy code in a String you can use the Eval class to execute it. Here's a simple example you can try out in the Groovy console:

def code = "2 + 2"
assert Eval.me(code) == 4
like image 197
Dónal Avatar answered Dec 11 '22 12:12

Dónal


Groovy can be concise and expressive, so you can quickly jump into the scripts to read or make changes, which means you might be able to just put your code into the scripts instead of into the database -- this is why you often see configurations done in code instead of properties or databases.

Anyway...

GroovyShell will allow you to evaluate any String you build as code, so you could write code to build one big string from your database, then pass it to GroovyShell.evaluate(String) to execute it.

Here's a sample:

#!/usr/bin/env groovy
new GroovyShell().evaluate("""
    @Grapes([
        @Grab("org.codehaus.geb:geb-core:0.6.0"),
        @Grab("org.seleniumhq.selenium:selenium-htmlunit-driver:2.0rc3")
    ])
    import geb.Browser

    Browser.drive {
        go "http://www.test.com/"
        $("form", name: "password").value("Test")
    }
""")

More simply, you could skip using GroovyShell within your own scripts and write the bit of code that reads the DB and generates the code and have it just dump the code to a file, then execute the new file any time you want. That file can serve as a sort of snapshot of what really got executed.

like image 37
John Flinchbaugh Avatar answered Dec 11 '22 12:12

John Flinchbaugh