// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;

public class EmbeddedR2 {
    public static class Data {
        public int iv;
        public String sv;
        public Data(int iv, String sv) {
            this.iv = iv;
            this.sv = sv;
        }
        public int getIv() {
            return iv;
        }
        public void setIv(int iv) {
            this.iv = iv;
        }
        public String getSv() {
            return sv;
        }
        public void setSv(String sv) {
            this.sv = sv;
        }
        public void m() {
            iv++;
            sv += "X";
        }
        @Override
        public String toString() {
            return String.format("(%d,%s)", iv, sv);
        }
    }
	public static void main(String[] args) throws ScriptException {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine se = sem.getEngineByName("Renjin");
        se.eval("for (i in 1:3) {\r\n" +
                "    print(\"Hi from R!\")\r\n" +
                "}\r\n");
        /*
        ScriptContext ctx = se.getContext();
        ctx.setAttribute("n", 3, ScriptContext.ENGINE_SCOPE);
        ctx.setAttribute("o", new Data(123, "ABC"), ScriptContext.ENGINE_SCOPE);
        se.eval("for (i in 1:n) {\r\n" +
                "    print(\"Hi from R!\")\r\n" +
                "}\r\n" +
                "o$iv = o$iv + 1L\r\n" +
                "o$sv = paste(o$sv, \"X\", sep=\"\")\r\n" +
                "o$m()\r\n", ctx);
        Data o = (Data)ctx.getAttribute("o");
        System.out.println(o);
        */
	}
}
