簡體   English   中英

如何將執行的 GROOVY 腳本結果返回到 REST API 響應

[英]How to return executed GROOVY script results to REST API Response

I am working to develop an REST API in spring boot that will accept any groovy script in request body and will execute it on server and return the executed results. 我試圖找出如何獲得腳本的執行結果,即使腳本明確沒有返回任何值。 這就像一個在線 groovy 編譯器,您可以在其中發布代碼並獲得結果

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.lang.Script;

public class GroovyController {
public static void main(String[] args) throws ScriptException {

   System.out.println(runScript());

}


public static String runScript(){
    String script = "class Student {\n" +
            "   private int StudentID;\n" +
            "   private String StudentName;\n" +
            "\t\n" +
            "   void setStudentID(int pID) {\n" +
            "      StudentID = pID;\n" +
            "   }\n" +
            "\t\n" +
            "   void setStudentName(String pName) {\n" +
            "      StudentName = pName;\n" +
            "   }\n" +
            "\t\n" +
            "   int getStudentID() {\n" +
            "      return this.StudentID;\n" +
            "   }\n" +
            "\t\n" +
            "   String getStudentName() {\n" +
            "      return this.StudentName;\n" +
            "   }\n" +
            "\t\n" +
            "   static void main(String[] args) {\n" +
            "      Student st = new Student();\n" +
            "      st.setStudentID(1);\n" +
            "      st.setStudentName(\"Joe\");\n" +
            "\t\t\n" +
            "      println(st.getStudentID());\n" +
            "      println(st.getStudentName());\n" +
            "   } \n" +
            "}";


    GroovyShell shell = new GroovyShell();

    Object result = shell.evaluate(script);
    return result.toString();

}

}

我已經弄清楚了如何在安全沙箱 model 中使用 java 運行 groovy 腳本。 I used run method of Groovy Shell class to run the groovy scripts with java. 如果執行的腳本本身返回任何值,例如return 2 * 4將返回 4,並且如果腳本沒有任何 return 語句並且 shell 的 run 方法將返回 null,則 Run 方法返回結果。

println("Hello world!!")的情況下,它不會明顯返回任何內容,但在 API 的請求負載中發送此腳本的客戶端會期望打印文本作為響應。 要捕獲 PrintStream 寫入的內容,可以使用綁定將自定義 PrintWriter 綁定到 GroovyShell 中的 object。 I had written a complete Spring Boot based Micro Service which exposes a REST API to execute Groovy Scripts on.the server in a secured sandbox model.

完整的微服務代碼可以在這里找到腳本執行服務

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM