Created
November 10, 2016 18:32
-
-
Save alex859/a4b405581bcd8fddbcd48dae4dac3919 to your computer and use it in GitHub Desktop.
Running groovy script in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import groovy.lang.GroovyRuntimeException; | |
import groovy.util.Eval; | |
import java.util.function.Predicate; | |
public class Test | |
{ | |
public static void main(String[] args) | |
{ | |
final Predicate<Facts> predicate = getPredicate("facts.name == 'Ale' && facts.subFacts.balance < 100"); | |
System.out.println(predicate.test(getFacts("Ale", 50))); // true | |
System.out.println(predicate.test(getFacts("Cicci", 50))); // false | |
} | |
private static Facts getFacts(final String name, final Integer balance) | |
{ | |
final Facts facts = new Facts(); | |
facts.setName(name); | |
final SubFacts subFacts = new SubFacts(); | |
subFacts.setBalance(balance); | |
facts.setSubFacts(subFacts); | |
return facts; | |
} | |
private static Predicate<Facts> getPredicate(final String expr) | |
{ | |
return facts -> | |
{ | |
try | |
{ | |
final Object result = Eval.me("facts", facts, expr); | |
if (result instanceof Boolean) | |
{ | |
return (Boolean) result; | |
} | |
throw new IllegalStateException("Invalid return type"); | |
} | |
catch (final GroovyRuntimeException exception) | |
{ | |
throw new IllegalStateException("Error compiling expression", exception); | |
} | |
}; | |
} | |
private static class Facts | |
{ | |
private String name; | |
private Integer number; | |
private SubFacts subFacts; | |
public String getName() | |
{ | |
return name; | |
} | |
public void setName(final String name) | |
{ | |
this.name = name; | |
} | |
public Integer getNumber() | |
{ | |
return number; | |
} | |
public void setNumber(final Integer number) | |
{ | |
this.number = number; | |
} | |
public SubFacts getSubFacts() | |
{ | |
return subFacts; | |
} | |
public void setSubFacts(final SubFacts subFacts) | |
{ | |
this.subFacts = subFacts; | |
} | |
} | |
private static class SubFacts | |
{ | |
private Integer balance; | |
public Integer getBalance() | |
{ | |
return balance; | |
} | |
public void setBalance(final Integer balance) | |
{ | |
this.balance = balance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment