use of jdk.nashorn.api.scripting.ScriptObjectMirror in project molgenis by molgenis.
the class JsMagmaScriptEvaluator method toScriptEngineValue.
private Object toScriptEngineValue(Entity entity, Attribute attr, int depth) {
Object value = null;
String attrName = attr.getName();
AttributeType attrType = attr.getDataType();
switch(attrType) {
case BOOL:
value = entity.getBoolean(attrName);
break;
case CATEGORICAL:
case FILE:
case XREF:
Entity xrefEntity = entity.getEntity(attrName);
value = toScriptEngineValueMap(xrefEntity, depth - 1);
break;
case CATEGORICAL_MREF:
case MREF:
case ONE_TO_MANY:
ScriptObjectMirror jsArray = null;
try {
jsArray = (ScriptObjectMirror) jsScriptEngine.eval("var arr = []; arr");
@SuppressWarnings("unchecked") List<Object> mrefValues = jsArray.to(List.class);
entity.getEntities(attrName).forEach(mrefEntity -> mrefValues.add(toScriptEngineValueMap(mrefEntity, depth - 1)));
} catch (javax.script.ScriptException ex) {
// Do not catch this error to allow
// the mapping service to collect errors to show in the UI
}
value = jsArray;
break;
case DATE:
LocalDate localDate = entity.getLocalDate(attrName);
if (localDate != null) {
value = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
break;
case DATE_TIME:
Instant instant = entity.getInstant(attrName);
if (instant != null) {
value = instant.toEpochMilli();
}
break;
case DECIMAL:
value = entity.getDouble(attrName);
break;
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case SCRIPT:
case STRING:
case TEXT:
value = entity.getString(attrName);
break;
case INT:
value = entity.getInt(attrName);
break;
case LONG:
value = entity.getLong(attrName);
break;
case COMPOUND:
throw new RuntimeException(format("Illegal attribute type [%s]", attrType.toString()));
default:
throw new UnexpectedEnumException(attrType);
}
return value;
}
use of jdk.nashorn.api.scripting.ScriptObjectMirror in project serverless by bluenimble.
the class ScriptableApiServiceSpi method execute.
@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
Object jsApi = ((SpecAndSpiPair) api.getHelper()).spec();
if (jsApi == null) {
throw new ApiServiceExecutionException("api '" + api.getNamespace() + "' doesn't support scripting");
}
SpecAndSpiPair serviceHelper = (SpecAndSpiPair) request.getService().getHelper();
Object spi = serviceHelper.spi();
if (spi == null) {
throw new ApiServiceExecutionException("service spi not found");
}
ScriptingEngine engine = api.space().feature(ScriptingEngine.class, ApiSpace.Features.Default, request);
if (!engine.has(spi, Functions.Execute)) {
return null;
}
// invoke execute
Object result = null;
try {
result = engine.invoke(spi, Functions.Execute, jsApi, consumer, request, response);
} catch (ScriptingEngineException ex) {
ex.setScript(Json.getString(request.getService().getRuntime(), Api.Spec.Runtime.Function));
throw new ApiServiceExecutionException(ex.getMessage(), ex);
}
if (result == null || (result instanceof Undefined)) {
return null;
}
if (ApiOutput.class.isAssignableFrom(result.getClass())) {
return (ApiOutput) result;
}
if (ScriptObjectMirror.class.isAssignableFrom(result.getClass())) {
ScriptObjectMirror som = (ScriptObjectMirror) result;
Object clazz = som.get(ClassField);
if (clazz == null) {
return new ApiSomOutput(som);
}
if (clazz.equals(ApiOutputClass)) {
return (ApiOutput) som.getMember(ProxyField);
}
}
Object converted = Converters.convert(result);
if (converted instanceof JsonArray) {
converted = new JsonObject().set(ApiOutput.Defaults.Items, converted);
}
if (!(converted instanceof JsonObject)) {
throw new ApiServiceExecutionException("result should be a valid json object");
}
return new JsonApiOutput((JsonObject) converted);
}
use of jdk.nashorn.api.scripting.ScriptObjectMirror in project serverless by bluenimble.
the class DefaultScriptingEngine method eval.
@Override
public Object eval(Supported supported, final Api api, ApiResource resource, ScriptContext sContext) throws ScriptingEngineException {
if (supported == null) {
throw new ScriptingEngineException("Unsupported Scripting Engine ");
}
ScriptEngine engine = engines.get(supported);
if (engine == null) {
throw new ScriptingEngineException("Unsupported Scripting Engine " + supported);
}
// get platform libs
ScriptObjectMirror libs = (ScriptObjectMirror) platform.get(Libs);
String[] libsKeys = libs.getOwnKeys(true);
CachedScript cached = scripts.get(resource.owner() + Lang.COLON + resource.path());
Reader reader = null;
if (cached == null || cached.timestamp < resource.timestamp().getTime()) {
InputStream rio = null;
try {
StringBuilder startScript = new StringBuilder(ScriptStart);
// add platform libraries
for (String lib : libsKeys) {
startScript.append(Var).append(Lang.SPACE).append(lib).append(Lang.EQUALS).append(Libs).append(Lang.DOT).append(lib).append(Lang.SEMICOLON);
}
startScript.append(Native);
for (String d : Denied) {
startScript.append(d);
}
String sStartScript = startScript.toString();
startScript.setLength(0);
rio = resource.toInput();
// format String script = platform.callMember (, arg);
List<InputStream> blocks = new ArrayList<InputStream>();
blocks.add(new ByteArrayInputStream(sStartScript.getBytes()));
blocks.add(rio);
blocks.add(new ByteArrayInputStream(ScriptEnd.getBytes()));
reader = new InputStreamReader(new SequenceInputStream(Collections.enumeration(blocks)));
cached = new CachedScript();
cached.script = ((Compilable) engine).compile(reader);
cached.timestamp = resource.timestamp().getTime();
scripts.put(resource.owner() + Lang.COLON + resource.path(), cached);
} catch (Exception e) {
throw new ScriptingEngineException(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(rio);
}
}
if (sContext == null) {
return null;
}
Bindings bindings = new SimpleBindings();
bindings.put(JavaClass, new Function<String, Class<?>>() {
@Override
public Class<?> apply(String type) {
try {
return api.getClassLoader().loadClass(type);
} catch (ClassNotFoundException cnfe) {
throw new RuntimeException(cnfe);
}
}
});
// add platform libraries
bindings.put(Libs, libs);
try {
Iterator<String> vars = sContext.vars();
while (vars.hasNext()) {
String var = vars.next();
bindings.put(var, sContext.var(var));
}
return cached.script.eval(bindings);
} catch (ScriptException e) {
throw new ScriptingEngineException(e.getMessage(), e);
} finally {
bindings.clear();
}
}
use of jdk.nashorn.api.scripting.ScriptObjectMirror in project serverless by bluenimble.
the class DefaultScriptingEngine method invoke.
@Override
public Object invoke(Object scriptable, String function, Object... args) throws ScriptingEngineException {
if (scriptable == null) {
scriptable = platform;
}
if (!(scriptable instanceof ScriptObjectMirror)) {
throw new ScriptingEngineException("object is not a valid scriptable object");
}
ScriptObjectMirror som = (ScriptObjectMirror) scriptable;
if (args != null && args.length > 0) {
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
if (arg == null || arg instanceof ScriptObjectMirror) {
continue;
}
Class<?> type = arg.getClass();
Scriptable ann = type.getAnnotation(Scriptable.class);
if (ann == null) {
continue;
}
Object jsArg = null;
if (Referenceable.class.isAssignableFrom(arg.getClass())) {
jsArg = ((Referenceable) arg).getReference();
}
if (jsArg == null) {
jsArg = platform.callMember(ann.name(), arg);
if (Referenceable.class.isAssignableFrom(arg.getClass())) {
((Referenceable) arg).setReference(jsArg);
}
}
args[i] = jsArg;
}
}
try {
return som.callMember(function, args);
} catch (Throwable err) {
throw new ScriptingEngineException(err.getMessage(), err);
}
}
use of jdk.nashorn.api.scripting.ScriptObjectMirror in project serverless by bluenimble.
the class ScriptingPlugin method init.
@Override
public void init(final ApiServer server) throws Exception {
if (Lang.isNullOrEmpty(vmArgs)) {
masterEngine = Manager.getScriptEngine(ScriptingPlugin.class.getClassLoader());
} else {
masterEngine = Manager.getScriptEngine(Lang.split(vmArgs, Lang.SPACE, true), ScriptingPlugin.class.getClassLoader());
}
Feature aFeature = ScriptingEngine.class.getAnnotation(Feature.class);
if (aFeature == null || Lang.isNullOrEmpty(aFeature.name())) {
return;
}
PackageClassLoader pcl = (PackageClassLoader) ScriptingPlugin.class.getClassLoader();
pcl.registerObject(Registered.ApiSpi, new ScriptableApiSpi());
pcl.registerObject(Registered.ServiceSpi, new ScriptableApiServiceSpi());
File platform = new File(home, "platform");
// load platform
Reader pReader = null;
try {
pReader = new FileReader(new File(platform, "Platform.js"));
Bindings bindings = new SimpleBindings();
bindings.put(Vars.Core, new File(platform, Vars.Core).getAbsolutePath());
bindings.put(Vars.Tools, new File(platform, Vars.Tools).getAbsolutePath());
shared = new DefaultScriptingEngine(this, (ScriptObjectMirror) masterEngine.eval(pReader, bindings), server.getMapProvider());
} finally {
IOUtils.closeQuietly(pReader);
}
// add features
server.addFeature(new ServerFeature() {
private static final long serialVersionUID = 2626039344401539390L;
@Override
public Class<?> type() {
return ScriptingEngine.class;
}
@Override
public Object get(ApiSpace space, String name) {
return shared;
}
@Override
public String provider() {
return ScriptingPlugin.this.getName();
}
@Override
public Plugin implementor() {
return ScriptingPlugin.this;
}
});
}
Aggregations