All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ats.generator.variables.transform.code.CodeEval Maven / Gradle / Ivy

The newest version!
package com.ats.generator.variables.transform.code;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Engine;
import org.graalvm.polyglot.io.IOAccess;

public class CodeEval {

	private static final String ERROR_CODE_EVAL = "#CodeEvalError#";
	
	private String type;
	private String code;

	public CodeEval(String type, String code) {
		this.type = type;
		this.code = code;
	}

	protected static Context getContext(ByteArrayOutputStream out, String type) {

		return Context.newBuilder(type)
				.engine(Engine.newBuilder()
						.logHandler(OutputStream.nullOutputStream())
						.option("engine.WarnInterpreterOnly", "false")
						.build())
				.useSystemExit(true)
				.allowIO(IOAccess.ALL)
				.allowAllAccess(true)
				.out(out)
				.build();
	}

	public String eval(){

		String result = null;
		final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		try (Context ct = getContext(outputStream, type)) {
			
			ct.eval(type, code);
			result = outputStream.toString();
			
		}catch(Exception e){
			result = ERROR_CODE_EVAL + e.getMessage();
		}

		return result.replace("\n", "");
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy