Skip to content

Instantly share code, notes, and snippets.

@int128
Created December 12, 2011 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save int128/1467965 to your computer and use it in GitHub Desktop.
Save int128/1467965 to your computer and use it in GitHub Desktop.
On the fly JavaScript evaluator
package org.hidetake.lab.controller.admin;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
public class EvaluateJavaScriptController extends Controller
{
@Override
public Navigation run() throws Exception
{
if(!validate()) {
throw new IllegalArgumentException(errors.toString());
}
String js = param("js");
Context context = Context.enter();
Scriptable scope = context.initStandardObjects();
String result = Context.toString(context.evaluateString(scope, js, null, 1, null));
Context.exit();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().append(result);
return null;
}
@Override
protected Navigation handleError(Throwable error) throws Throwable
{
StringWriter writer = new StringWriter();
error.printStackTrace(new PrintWriter(writer));
String message = writer.getBuffer().toString().replaceAll("\t.*\r?\n", "");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().append(message);
return null;
}
private boolean validate()
{
Validators v = new Validators(request);
v.add("js", v.required());
return v.validate();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment