2

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
5
  • My gut reaction is that this is an X-Y problem. What’s the ultimate goal here? Commented Sep 6, 2018 at 14:11
  • Goal is to get user input to remove any special character from a string. removeSpecialChars variable gets user input through ajax. Commented Sep 6, 2018 at 14:18
  • How do you create engine? Commented Sep 6, 2018 at 14:19
  • Added script engine in question. Commented Sep 6, 2018 at 14:21
  • Why do you need to script this? If the raw values come why can't you just use those as--all? Commented Sep 6, 2018 at 15:03

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks buddy! It was very much informational, I will make sure to add security layer for user inputs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.