Search in sources :

Example 11 with MissingPropertyException

use of groovy.lang.MissingPropertyException in project groovy-core by groovy.

the class GroovyScriptEngineImpl method eval.

// package-privates
Object eval(Class scriptClass, final ScriptContext ctx) throws ScriptException {
    // Only initialize once.
    if (null == ctx.getAttribute("context", ScriptContext.ENGINE_SCOPE)) {
        // add context to bindings
        ctx.setAttribute("context", ctx, ScriptContext.ENGINE_SCOPE);
        // direct output to ctx.getWriter
        // If we're wrapping with a PrintWriter here,
        // enable autoFlush because otherwise it might not get done!
        final Writer writer = ctx.getWriter();
        ctx.setAttribute("out", (writer instanceof PrintWriter) ? writer : new PrintWriter(writer, true), ScriptContext.ENGINE_SCOPE);
    // Not going to do this after all (at least for now).
    // Scripts can use context.{reader, writer, errorWriter}.
    // That is a modern version of System.{in, out, err} or Console.{reader, writer}().
    //
    //            // New I/O names consistent with ScriptContext and java.io.Console.
    //
    //            ctx.setAttribute("writer", writer, ScriptContext.ENGINE_SCOPE);
    //
    //            // Direct errors to ctx.getErrorWriter
    //            final Writer errorWriter = ctx.getErrorWriter();
    //            ctx.setAttribute("errorWriter", (errorWriter instanceof PrintWriter) ?
    //                                    errorWriter :
    //                                    new PrintWriter(errorWriter),
    //                                    ScriptContext.ENGINE_SCOPE);
    //
    //            // Get input from ctx.getReader
    //            // We don't wrap with BufferedReader here because we expect that if
    //            // the host wants that they do it.  Either way Groovy scripts will
    //            // always have readLine because the GDK supplies it for Reader.
    //            ctx.setAttribute("reader", ctx.getReader(), ScriptContext.ENGINE_SCOPE);
    }
    // Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for differents groovy script
    if (ctx.getWriter() != null) {
        ctx.setAttribute("out", new PrintWriter(ctx.getWriter(), true), ScriptContext.ENGINE_SCOPE);
    }
    /*
         * We use the following Binding instance so that global variable lookup
         * will be done in the current ScriptContext instance.
         */
    Binding binding = new Binding(ctx.getBindings(ScriptContext.ENGINE_SCOPE)) {

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

        @Override
        public void setVariable(String name, Object value) {
            synchronized (ctx) {
                int scope = ctx.getAttributesScope(name);
                if (scope == -1) {
                    scope = ScriptContext.ENGINE_SCOPE;
                }
                ctx.setAttribute(name, value, scope);
            }
        }
    };
    try {
        // then simply return that class
        if (!Script.class.isAssignableFrom(scriptClass)) {
            return scriptClass;
        } else {
            // it's a script
            Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
            // save all current closures into global closures map
            Method[] methods = scriptClass.getMethods();
            for (Method m : methods) {
                String name = m.getName();
                globalClosures.put(name, new MethodClosure(scriptObject, name));
            }
            MetaClass oldMetaClass = scriptObject.getMetaClass();
            /*
                * We override the MetaClass of this script object so that we can
                * forward calls to global closures (of previous or future "eval" calls)
                * This gives the illusion of working on the same "global" scope.
                */
            scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {

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

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

                @Override
                public Object invokeStaticMethod(Object object, String name, Object[] args) {
                    try {
                        return super.invokeStaticMethod(object, name, args);
                    } catch (MissingMethodException mme) {
                        return callGlobal(name, args, ctx);
                    }
                }
            });
            return scriptObject.run();
        }
    } catch (Exception e) {
        throw new ScriptException(e);
    } finally {
        // Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for different groovy script
        // Groovy's scripting engine implementation adds those two variables in the binding
        // but should clean up afterwards
        ctx.removeAttribute("context", ScriptContext.ENGINE_SCOPE);
        ctx.removeAttribute("out", ScriptContext.ENGINE_SCOPE);
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) CompiledScript(javax.script.CompiledScript) MissingPropertyException(groovy.lang.MissingPropertyException) String(java.lang.String) 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) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) Tuple(groovy.lang.Tuple) PrintWriter(java.io.PrintWriter)

Example 12 with MissingPropertyException

use of groovy.lang.MissingPropertyException in project groovy-core by groovy.

the class ObjectGraphBuilder method resolveLazyReferences.

private void resolveLazyReferences() {
    if (!lazyReferencesAllowed)
        return;
    for (NodeReference ref : lazyReferences) {
        if (ref.parent == null)
            continue;
        Object child = null;
        try {
            child = getProperty(ref.refId);
        } catch (MissingPropertyException mpe) {
        // ignore
        }
        if (child == null) {
            throw new IllegalArgumentException("There is no valid node for reference " + ref.parentName + "." + ref.childName + "=" + ref.refId);
        }
        // set child first
        childPropertySetter.setChild(ref.parent, child, ref.parentName, relationNameResolver.resolveChildRelationName(ref.parentName, ref.parent, ref.childName, child));
        // set parent afterwards
        String propertyName = relationNameResolver.resolveParentRelationName(ref.parentName, ref.parent, ref.childName, child);
        MetaProperty metaProperty = InvokerHelper.getMetaClass(child).hasProperty(child, propertyName);
        if (metaProperty != null) {
            metaProperty.setProperty(child, ref.parent);
        }
    }
}
Also used : MissingPropertyException(groovy.lang.MissingPropertyException) GString(groovy.lang.GString) MetaProperty(groovy.lang.MetaProperty)

Example 13 with MissingPropertyException

use of groovy.lang.MissingPropertyException in project groovy by apache.

the class Sql method getUpdatedParams.

public List<Object> getUpdatedParams(List<Object> params, List<Tuple> indexPropList) {
    List<Object> updatedParams = new ArrayList<Object>();
    for (Tuple tuple : indexPropList) {
        int index = (Integer) tuple.get(0);
        String prop = (String) tuple.get(1);
        if (index < 0 || index >= params.size())
            throw new IllegalArgumentException("Invalid index " + index + " should be in range 1.." + params.size());
        try {
            updatedParams.add(prop.equals("<this>") ? params.get(index) : InvokerHelper.getProperty(params.get(index), prop));
        } catch (MissingPropertyException mpe) {
            throw new IllegalArgumentException("Property '" + prop + "' not found for parameter " + index);
        }
    }
    return updatedParams;
}
Also used : MissingPropertyException(groovy.lang.MissingPropertyException) GString(groovy.lang.GString) Tuple(groovy.lang.Tuple)

Example 14 with MissingPropertyException

use of groovy.lang.MissingPropertyException in project groovy by apache.

the class InvokerHelper method createScript.

public static Script createScript(Class scriptClass, Binding context) {
    Script script;
    if (scriptClass == null) {
        script = new NullScript(context);
    } else {
        try {
            if (Script.class.isAssignableFrom(scriptClass)) {
                try {
                    Constructor constructor = scriptClass.getConstructor(Binding.class);
                    script = (Script) constructor.newInstance(context);
                } catch (NoSuchMethodException e) {
                    // Fallback for non-standard "Script" classes.
                    script = (Script) scriptClass.newInstance();
                    script.setBinding(context);
                }
            } else {
                final GroovyObject object = (GroovyObject) scriptClass.newInstance();
                // it could just be a class, so let's wrap it in a Script
                // wrapper; though the bindings will be ignored
                script = new Script(context) {

                    public Object run() {
                        Object argsToPass = EMPTY_MAIN_ARGS;
                        try {
                            Object args = getProperty("args");
                            if (args instanceof String[]) {
                                argsToPass = args;
                            }
                        } catch (MissingPropertyException e) {
                        // They'll get empty args since none exist in the context.
                        }
                        object.invokeMethod("main", argsToPass);
                        return null;
                    }
                };
                Map variables = context.getVariables();
                MetaClass mc = getMetaClass(object);
                for (Object o : variables.entrySet()) {
                    Map.Entry entry = (Map.Entry) o;
                    String key = entry.getKey().toString();
                    // assume underscore variables are for the wrapper script
                    setPropertySafe(key.startsWith("_") ? script : object, mc, key, entry.getValue());
                }
            }
        } catch (Exception e) {
            throw new GroovyRuntimeException("Failed to create Script instance for class: " + scriptClass + ". Reason: " + e, e);
        }
    }
    return script;
}
Also used : Script(groovy.lang.Script) Constructor(java.lang.reflect.Constructor) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) MissingPropertyException(groovy.lang.MissingPropertyException) GString(groovy.lang.GString) MissingPropertyException(groovy.lang.MissingPropertyException) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) MissingMethodException(groovy.lang.MissingMethodException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SpreadMapEvaluatingException(groovy.lang.SpreadMapEvaluatingException) IOException(java.io.IOException) GroovyObject(groovy.lang.GroovyObject) MetaClass(groovy.lang.MetaClass) GroovyObject(groovy.lang.GroovyObject) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) SpreadMap(groovy.lang.SpreadMap)

Example 15 with MissingPropertyException

use of groovy.lang.MissingPropertyException in project groovy by apache.

the class ObjectGraphBuilder method resolveLazyReferences.

private void resolveLazyReferences() {
    if (!lazyReferencesAllowed)
        return;
    for (NodeReference ref : lazyReferences) {
        if (ref.parent == null)
            continue;
        Object child = null;
        try {
            child = getProperty(ref.refId);
        } catch (MissingPropertyException mpe) {
        // ignore
        }
        if (child == null) {
            throw new IllegalArgumentException("There is no valid node for reference " + ref.parentName + "." + ref.childName + "=" + ref.refId);
        }
        // set child first
        childPropertySetter.setChild(ref.parent, child, ref.parentName, relationNameResolver.resolveChildRelationName(ref.parentName, ref.parent, ref.childName, child));
        // set parent afterwards
        String propertyName = relationNameResolver.resolveParentRelationName(ref.parentName, ref.parent, ref.childName, child);
        MetaProperty metaProperty = InvokerHelper.getMetaClass(child).hasProperty(child, propertyName);
        if (metaProperty != null) {
            metaProperty.setProperty(child, ref.parent);
        }
    }
}
Also used : MissingPropertyException(groovy.lang.MissingPropertyException) GString(groovy.lang.GString) MetaProperty(groovy.lang.MetaProperty)

Aggregations

MissingPropertyException (groovy.lang.MissingPropertyException)16 GString (groovy.lang.GString)4 MetaClass (groovy.lang.MetaClass)4 MissingMethodException (groovy.lang.MissingMethodException)4 Script (groovy.lang.Script)4 Tuple (groovy.lang.Tuple)4 IOException (java.io.IOException)4 Binding (groovy.lang.Binding)3 DelegatingMetaClass (groovy.lang.DelegatingMetaClass)3 PrintWriter (java.io.PrintWriter)3 Method (java.lang.reflect.Method)3 CompiledScript (javax.script.CompiledScript)3 ScriptException (javax.script.ScriptException)3 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)3 MethodClosure (org.codehaus.groovy.runtime.MethodClosure)3 MetaProperty (groovy.lang.MetaProperty)2 Range (groovy.lang.Range)2 Writer (java.io.Writer)2 SQLException (java.sql.SQLException)2 Iterator (java.util.Iterator)2