Search in sources :

Example 36 with ScriptObjectMirror

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;
}
Also used : Entity(org.molgenis.data.Entity) ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) Instant(java.time.Instant) LocalDate(java.time.LocalDate) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) AttributeType(org.molgenis.data.meta.AttributeType)

Example 37 with ScriptObjectMirror

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);
}
Also used : JsonArray(com.bluenimble.platform.json.JsonArray) Undefined(jdk.nashorn.internal.runtime.Undefined) ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) ApiOutput(com.bluenimble.platform.api.ApiOutput) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput) ScriptingEngineException(com.bluenimble.platform.scripting.ScriptingEngineException) ApiServiceExecutionException(com.bluenimble.platform.api.ApiServiceExecutionException) JsonObject(com.bluenimble.platform.json.JsonObject) JsonObject(com.bluenimble.platform.json.JsonObject) ScriptingEngine(com.bluenimble.platform.scripting.ScriptingEngine) JsonApiOutput(com.bluenimble.platform.api.impls.JsonApiOutput)

Example 38 with ScriptObjectMirror

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();
    }
}
Also used : ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) ScriptEngine(javax.script.ScriptEngine) ScriptingEngineException(com.bluenimble.platform.scripting.ScriptingEngineException) ScriptException(javax.script.ScriptException) ScriptException(javax.script.ScriptException) SequenceInputStream(java.io.SequenceInputStream) ScriptingEngineException(com.bluenimble.platform.scripting.ScriptingEngineException) ByteArrayInputStream(java.io.ByteArrayInputStream) SimpleBindings(javax.script.SimpleBindings)

Example 39 with ScriptObjectMirror

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);
    }
}
Also used : ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) Referenceable(com.bluenimble.platform.Referenceable) ScriptingEngineException(com.bluenimble.platform.scripting.ScriptingEngineException) Scriptable(com.bluenimble.platform.scripting.Scriptable)

Example 40 with ScriptObjectMirror

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;
        }
    });
}
Also used : ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) DefaultScriptingEngine(com.bluenimble.platform.api.scripting.impls.DefaultScriptingEngine) Reader(java.io.Reader) FileReader(java.io.FileReader) Feature(com.bluenimble.platform.Feature) ServerFeature(com.bluenimble.platform.server.ServerFeature) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) ScriptableApiServiceSpi(com.bluenimble.platform.api.impls.scripting.ScriptableApiServiceSpi) ServerFeature(com.bluenimble.platform.server.ServerFeature) ApiSpace(com.bluenimble.platform.api.ApiSpace) SimpleBindings(javax.script.SimpleBindings) ScriptableApiSpi(com.bluenimble.platform.api.impls.scripting.ScriptableApiSpi) FileReader(java.io.FileReader) File(java.io.File) PackageClassLoader(com.bluenimble.platform.PackageClassLoader) Plugin(com.bluenimble.platform.plugins.Plugin) AbstractPlugin(com.bluenimble.platform.plugins.impls.AbstractPlugin)

Aggregations

ScriptObjectMirror (jdk.nashorn.api.scripting.ScriptObjectMirror)76 Test (org.junit.Test)34 InteractiveScriptSession (org.phoenicis.scripts.interpreter.InteractiveScriptSession)28 ScriptInterpreter (org.phoenicis.scripts.interpreter.ScriptInterpreter)28 Consumer (java.util.function.Consumer)27 List (java.util.List)23 LoggerFactory (org.slf4j.LoggerFactory)20 File (java.io.File)17 IOException (java.io.IOException)17 Logger (org.slf4j.Logger)14 WinePrefixContainerDTO (org.phoenicis.containers.dto.WinePrefixContainerDTO)12 Map (java.util.Map)11 ArrayList (java.util.ArrayList)10 RegistryParameter (org.phoenicis.containers.wine.parameters.RegistryParameter)10 LibraryManager (org.phoenicis.library.LibraryManager)10 ShortcutManager (org.phoenicis.library.ShortcutManager)10 ShortcutCategoryDTO (org.phoenicis.library.dto.ShortcutCategoryDTO)10 ShortcutDTO (org.phoenicis.library.dto.ShortcutDTO)10 RegistryWriter (org.phoenicis.win32.registry.RegistryWriter)10 URI (java.net.URI)8