Created
December 12, 2011 15:49
-
-
Save int128/1467965 to your computer and use it in GitHub Desktop.
On the fly JavaScript evaluator
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
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