Sks
Sks

Reputation: 610

Evaluate java expression using groovy

I am getting hard time in evaluating java expression using groovy. Below is my code where I have to dynamically push replace statements and evaluate it. replaceSpecialChars value comes from user input.

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("groovy");
String text =  "Disa";
System.out.println(text); //1
text = text.replace("s", "");
System.out.println(text); //2
String removeSpecialChars =  ".replace('a','')";
text = text + removeSpecialChars;
System.out.println(text); //3
engine.put("first", text);
System.out.println(engine.eval("first")); //4

4 Sysout Outputs -

Disa 
Dia 
Dia.replace('a','')
Dia.replace('a','')

Expected Outputs -

Disa
Dia
Dia.replace('a','')
Di

Upvotes: 2

Views: 519

Answers (1)

dpr
dpr

Reputation: 10964

You should be able to do something like this:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("groovy");
removeSpecialChars = ".replace('a','')";
text = "Dia";
engine.put("first", text);
result = engine.eval("first" + removeSpecialChars);
System.out.println(result);

By calling engine.put("first", text); you create a variable first with the String Dia.replace('a','') as value. Evaluating this variable is simply a noop, that's why you get the same value as result again.

You can furthermore shorten the above to

result = engine.eval("\"" + text + "\"" + removeSpecialChars);

Try it out on glot.io: https://glot.io/snippets/f4jyrbt92h

You should however probably be very careful with what operations you allow and need to make sure malicious user input will not screw your whole system. If for example the user input is .replace('a',''); file("C:/Windows/").delete(); this might be something you don't want to execute. In general accepting user input for dynamic code execution makes your system an easy target for all kind of exploits.

Upvotes: 1

Related Questions