Search in sources :

Example 66 with ScriptException

use of javax.script.ScriptException in project gremlin by tinkerpop.

the class GremlinGroovyScriptEngineTest method testThreadSafetyOnCompiledScript.

public void testThreadSafetyOnCompiledScript() throws Exception {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(10);
    final CompiledScript script = engine.compile("pipe = g.V('name',name); if(pipe.hasNext()) { pipe.out.count() } else { null }");
    int runs = 500;
    final CountDownLatch latch = new CountDownLatch(runs);
    final List<String> names = Arrays.asList("marko", "peter", "josh", "vadas", "stephen", "pavel", "matthias");
    final Random random = new Random();
    for (int i = 0; i < runs; i++) {
        new Thread() {

            public void run() {
                String name = names.get(random.nextInt(names.size() - 1));
                try {
                    final Bindings bindings = engine.createBindings();
                    bindings.put("g", TinkerGraphFactory.createTinkerGraph());
                    bindings.put("name", name);
                    Object result = script.eval(bindings);
                    if (name.equals("stephen") || name.equals("pavel") || name.equals("matthias"))
                        assertNull(result);
                    else
                        assertNotNull(result);
                } catch (ScriptException e) {
                    //System.out.println(e);
                    assertFalse(true);
                }
                latch.countDown();
            }
        }.start();
    }
    latch.await();
}
Also used : CompiledScript(javax.script.CompiledScript) ScriptException(javax.script.ScriptException) CountDownLatch(java.util.concurrent.CountDownLatch) Bindings(javax.script.Bindings)

Example 67 with ScriptException

use of javax.script.ScriptException in project gremlin by tinkerpop.

the class GremlinGroovyScriptEngine method eval.

Object eval(final Class scriptClass, final ScriptContext context) throws ScriptException {
    this.checkClearCache();
    context.setAttribute("context", context, ScriptContext.ENGINE_SCOPE);
    java.io.Writer writer = context.getWriter();
    context.setAttribute("out", writer instanceof PrintWriter ? writer : new PrintWriter(writer), ScriptContext.ENGINE_SCOPE);
    Binding binding = new Binding() {

        public Object getVariable(String name) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope != -1) {
                    return context.getAttribute(name, scope);
                }
                throw new MissingPropertyException(name, getClass());
            }
        }

        public void setVariable(String name, Object value) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope == -1) {
                    scope = ScriptContext.ENGINE_SCOPE;
                }
                context.setAttribute(name, value, scope);
            }
        }
    };
    try {
        Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
        Method[] methods = scriptClass.getMethods();
        Map<String, MethodClosure> closures = new HashMap<String, MethodClosure>();
        for (Method m : methods) {
            String name = m.getName();
            closures.put(name, new MethodClosure(scriptObject, name));
        }
        globalClosures.putAll(closures);
        final MetaClass oldMetaClass = scriptObject.getMetaClass();
        scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {

            public Object invokeMethod(Object object, String name, Object args) {
                if (args == null) {
                    return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
                } else if (args instanceof Tuple) {
                    return invokeMethod(object, name, ((Tuple) args).toArray());
                } else if (args instanceof Object[]) {
                    return invokeMethod(object, name, (Object[]) args);
                } else {
                    return invokeMethod(object, name, new Object[] { args });
                }
            }

            public Object invokeMethod(Object object, String name, Object[] args) {
                try {
                    return super.invokeMethod(object, name, args);
                } catch (MissingMethodException mme) {
                    return callGlobal(name, args, context);
                }
            }

            public Object invokeStaticMethod(Object object, String name, Object[] args) {
                try {
                    return super.invokeStaticMethod(object, name, args);
                } catch (MissingMethodException mme) {
                    return callGlobal(name, args, context);
                }
            }
        });
        return scriptObject.run();
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) CompiledScript(javax.script.CompiledScript) GroovyCompiledScript(org.codehaus.groovy.jsr223.GroovyCompiledScript) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MissingPropertyException(groovy.lang.MissingPropertyException) Method(java.lang.reflect.Method) MethodClosure(org.codehaus.groovy.runtime.MethodClosure) MissingPropertyException(groovy.lang.MissingPropertyException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) IOException(java.io.IOException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) MetaClass(groovy.lang.MetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) Tuple(groovy.lang.Tuple) PrintWriter(java.io.PrintWriter)

Example 68 with ScriptException

use of javax.script.ScriptException in project sass-maven-plugin by Jasig.

the class AbstractSassMojo method executeSassScript.

/**
     * Execute the SASS Compilation Ruby Script
     */
protected void executeSassScript(String sassScript) throws MojoExecutionException, MojoFailureException {
    final Log log = this.getLog();
    System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe");
    log.debug("Execute SASS Ruby Script:\n" + sassScript);
    final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby");
    try {
        CompilerCallback compilerCallback = new CompilerCallback(log);
        jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback);
        jruby.eval(sassScript);
        if (failOnError && compilerCallback.hadError()) {
            throw new MojoFailureException("SASS compilation encountered errors (see above for details).");
        }
    } catch (final ScriptException e) {
        throw new MojoExecutionException("Failed to execute SASS ruby script:\n" + sassScript, e);
    }
}
Also used : ScriptException(javax.script.ScriptException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Log(org.apache.maven.plugin.logging.Log) ScriptEngineManager(javax.script.ScriptEngineManager) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ScriptEngine(javax.script.ScriptEngine)

Example 69 with ScriptException

use of javax.script.ScriptException in project spring-framework by spring-projects.

the class ScriptTemplateView method renderMergedOutputModel.

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        ScriptEngine engine = getEngine();
        Invocable invocable = (Invocable) engine;
        String url = getUrl();
        String template = getTemplate(url);
        Function<String, String> templateLoader = path -> {
            try {
                return getTemplate(path);
            } catch (IOException ex) {
                throw new IllegalStateException(ex);
            }
        };
        RenderingContext context = new RenderingContext(this.getApplicationContext(), this.locale, templateLoader, url);
        Object html;
        if (this.renderObject != null) {
            Object thiz = engine.eval(this.renderObject);
            html = invocable.invokeMethod(thiz, this.renderFunction, template, model, context);
        } else {
            html = invocable.invokeFunction(this.renderFunction, template, model, context);
        }
        response.getWriter().write(String.valueOf(html));
    } catch (ScriptException ex) {
        throw new ServletException("Failed to render script template", new StandardScriptEvalException(ex));
    }
}
Also used : Arrays(java.util.Arrays) ServletException(javax.servlet.ServletException) BeanFactoryUtils(org.springframework.beans.factory.BeanFactoryUtils) HashMap(java.util.HashMap) ApplicationContextException(org.springframework.context.ApplicationContextException) Function(java.util.function.Function) StandardScriptUtils(org.springframework.scripting.support.StandardScriptUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) Charset(java.nio.charset.Charset) Locale(java.util.Locale) Map(java.util.Map) ScriptException(javax.script.ScriptException) Resource(org.springframework.core.io.Resource) ResourceLoader(org.springframework.core.io.ResourceLoader) ObjectUtils(org.springframework.util.ObjectUtils) HttpServletResponse(javax.servlet.http.HttpServletResponse) ScriptEngineManager(javax.script.ScriptEngineManager) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) InputStreamReader(java.io.InputStreamReader) ApplicationContext(org.springframework.context.ApplicationContext) StandardCharsets(java.nio.charset.StandardCharsets) NamedThreadLocal(org.springframework.core.NamedThreadLocal) Invocable(javax.script.Invocable) AbstractUrlBasedView(org.springframework.web.servlet.view.AbstractUrlBasedView) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ScriptEngine(javax.script.ScriptEngine) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) FileCopyUtils(org.springframework.util.FileCopyUtils) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) ServletException(javax.servlet.ServletException) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) IOException(java.io.IOException) ScriptEngine(javax.script.ScriptEngine)

Example 70 with ScriptException

use of javax.script.ScriptException in project spring-framework by spring-projects.

the class ScriptTemplateView method renderInternal.

@Override
protected Mono<Void> renderInternal(Map<String, Object> model, MediaType contentType, ServerWebExchange exchange) {
    return Mono.defer(() -> {
        ServerHttpResponse response = exchange.getResponse();
        try {
            ScriptEngine engine = getEngine();
            Invocable invocable = (Invocable) engine;
            String url = getUrl();
            String template = getTemplate(url);
            Function<String, String> templateLoader = path -> {
                try {
                    return getTemplate(path);
                } catch (IOException ex) {
                    throw new IllegalStateException(ex);
                }
            };
            RenderingContext context = new RenderingContext(this.getApplicationContext(), this.locale, templateLoader, url);
            Object html;
            if (this.renderObject != null) {
                Object thiz = engine.eval(this.renderObject);
                html = invocable.invokeMethod(thiz, this.renderFunction, template, model, context);
            } else {
                html = invocable.invokeFunction(this.renderFunction, template, model, context);
            }
            byte[] bytes = String.valueOf(html).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().allocateBuffer(bytes.length).write(bytes);
            return response.writeWith(Mono.just(buffer));
        } catch (ScriptException ex) {
            throw new IllegalStateException("Failed to render script template", new StandardScriptEvalException(ex));
        } catch (Exception ex) {
            throw new IllegalStateException("Failed to render script template", ex);
        }
    });
}
Also used : ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) BeanFactoryUtils(org.springframework.beans.factory.BeanFactoryUtils) ApplicationContextException(org.springframework.context.ApplicationContextException) Function(java.util.function.Function) StandardScriptUtils(org.springframework.scripting.support.StandardScriptUtils) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Locale(java.util.Locale) Map(java.util.Map) ScriptException(javax.script.ScriptException) Resource(org.springframework.core.io.Resource) AbstractUrlBasedView(org.springframework.web.reactive.result.view.AbstractUrlBasedView) ResourceLoader(org.springframework.core.io.ResourceLoader) MediaType(org.springframework.http.MediaType) ObjectUtils(org.springframework.util.ObjectUtils) ScriptEngineManager(javax.script.ScriptEngineManager) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) BeansException(org.springframework.beans.BeansException) DataBuffer(org.springframework.core.io.buffer.DataBuffer) InputStreamReader(java.io.InputStreamReader) ApplicationContext(org.springframework.context.ApplicationContext) StandardCharsets(java.nio.charset.StandardCharsets) Invocable(javax.script.Invocable) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ScriptEngine(javax.script.ScriptEngine) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) FileCopyUtils(org.springframework.util.FileCopyUtils) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) IOException(java.io.IOException) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) ScriptEngine(javax.script.ScriptEngine) ApplicationContextException(org.springframework.context.ApplicationContextException) ScriptException(javax.script.ScriptException) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Aggregations

ScriptException (javax.script.ScriptException)106 ScriptEngine (javax.script.ScriptEngine)42 IOException (java.io.IOException)41 Bindings (javax.script.Bindings)30 ScriptEngineManager (javax.script.ScriptEngineManager)20 InputStreamReader (java.io.InputStreamReader)12 CompiledScript (javax.script.CompiledScript)12 Map (java.util.Map)11 Invocable (javax.script.Invocable)11 ScriptContext (javax.script.ScriptContext)11 SimpleBindings (javax.script.SimpleBindings)10 File (java.io.File)8 Reader (java.io.Reader)7 Writer (java.io.Writer)7 HashMap (java.util.HashMap)7 PrintWriter (java.io.PrintWriter)6 ArrayList (java.util.ArrayList)6 SlingBindings (org.apache.sling.api.scripting.SlingBindings)6 MissingMethodException (groovy.lang.MissingMethodException)5 MissingPropertyException (groovy.lang.MissingPropertyException)5