Search in sources :

Example 51 with GroovyRuntimeException

use of groovy.lang.GroovyRuntimeException in project intellij-community by JetBrains.

the class ScriptSupport method evaluate.

public String evaluate(MatchResult result, PsiElement context) {
    try {
        final HashMap<String, Object> variableMap = new HashMap<>();
        variableMap.put(ScriptLog.SCRIPT_LOG_VAR_NAME, myScriptLog);
        if (result != null) {
            buildVariableMap(result, variableMap);
            if (context == null) {
                context = result.getMatch();
            }
        }
        context = StructuralSearchUtil.getPresentableElement(context);
        variableMap.put(myName, context);
        variableMap.put(Configuration.CONTEXT_VAR_NAME, context);
        script.setBinding(new Binding(variableMap));
        final Object o = script.run();
        return String.valueOf(o);
    } catch (GroovyRuntimeException ex) {
        throw new StructuralSearchException(SSRBundle.message("groovy.script.error", ex.getMessage()));
    } finally {
        script.setBinding(null);
    }
}
Also used : Binding(groovy.lang.Binding) StructuralSearchException(com.intellij.structuralsearch.StructuralSearchException) HashMap(java.util.HashMap) GroovyRuntimeException(groovy.lang.GroovyRuntimeException)

Example 52 with GroovyRuntimeException

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

the class AsmClassGenerator method visitClass.

// GroovyClassVisitor interface
//-------------------------------------------------------------------------
public void visitClass(ClassNode classNode) {
    referencedClasses.clear();
    WriterControllerFactory factory = (WriterControllerFactory) classNode.getNodeMetaData(WriterControllerFactory.class);
    WriterController normalController = new WriterController();
    if (factory != null) {
        this.controller = factory.makeController(normalController);
    } else {
        this.controller = normalController;
    }
    this.controller.init(this, context, cv, classNode);
    if (controller.shouldOptimizeForInt() || factory != null) {
        OptimizingStatementWriter.setNodeMeta(controller.getTypeChooser(), classNode);
    }
    try {
        cv.visit(controller.getBytecodeVersion(), adjustedClassModifiersForClassWriting(classNode), controller.getInternalClassName(), BytecodeHelper.getGenericsSignature(classNode), controller.getInternalBaseClassName(), BytecodeHelper.getClassInternalNames(classNode.getInterfaces()));
        cv.visitSource(sourceFile, null);
        if (classNode instanceof InnerClassNode) {
            InnerClassNode innerClass = (InnerClassNode) classNode;
            MethodNode enclosingMethod = innerClass.getEnclosingMethod();
            if (enclosingMethod != null) {
                String outerClassName = BytecodeHelper.getClassInternalName(innerClass.getOuterClass().getName());
                cv.visitOuterClass(outerClassName, enclosingMethod.getName(), BytecodeHelper.getMethodDescriptor(enclosingMethod));
            }
        }
        if (classNode.getName().endsWith("package-info")) {
            PackageNode packageNode = classNode.getPackage();
            if (packageNode != null) {
                // pull them out of package node but treat them like they were on class node
                for (AnnotationNode an : packageNode.getAnnotations()) {
                    // skip built-in properties
                    if (an.isBuiltIn())
                        continue;
                    if (an.hasSourceRetention())
                        continue;
                    AnnotationVisitor av = getAnnotationVisitor(classNode, an, cv);
                    visitAnnotationAttributes(an, av);
                    av.visitEnd();
                }
            }
            cv.visitEnd();
            return;
        } else {
            visitAnnotations(classNode, cv);
        }
        if (classNode.isInterface()) {
            ClassNode owner = classNode;
            if (owner instanceof InnerClassNode) {
                owner = owner.getOuterClass();
            }
            String outerClassName = classNode.getName();
            String name = outerClassName + "$" + context.getNextInnerClassIdx();
            controller.setInterfaceClassLoadingClass(new InterfaceHelperClassNode(owner, name, ACC_SUPER | ACC_SYNTHETIC | ACC_STATIC, ClassHelper.OBJECT_TYPE, controller.getCallSiteWriter().getCallSites()));
            super.visitClass(classNode);
            createInterfaceSyntheticStaticFields();
        } else {
            super.visitClass(classNode);
            MopWriter.Factory mopWriterFactory = classNode.getNodeMetaData(MopWriter.Factory.class);
            if (mopWriterFactory == null) {
                mopWriterFactory = MopWriter.FACTORY;
            }
            MopWriter mopWriter = mopWriterFactory.create(controller);
            mopWriter.createMopMethods();
            controller.getCallSiteWriter().generateCallSiteArray();
            createSyntheticStaticFields();
        }
        // GROOVY-6750 and GROOVY-6808
        for (Iterator<InnerClassNode> iter = classNode.getInnerClasses(); iter.hasNext(); ) {
            InnerClassNode innerClass = iter.next();
            makeInnerClassEntry(innerClass);
        }
        makeInnerClassEntry(classNode);
        cv.visitEnd();
    } catch (GroovyRuntimeException e) {
        e.setModule(classNode.getModule());
        throw e;
    } catch (NegativeArraySizeException nase) {
        throw new GroovyRuntimeException("NegativeArraySizeException while processing " + sourceFile, nase);
    } catch (NullPointerException npe) {
        throw new GroovyRuntimeException("NPE while processing " + sourceFile, npe);
    }
}
Also used : InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) InterfaceHelperClassNode(org.codehaus.groovy.ast.InterfaceHelperClassNode) ClassNode(org.codehaus.groovy.ast.ClassNode) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) WriterController(org.codehaus.groovy.classgen.asm.WriterController) MethodNode(org.codehaus.groovy.ast.MethodNode) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) AnnotationVisitor(org.objectweb.asm.AnnotationVisitor) InterfaceHelperClassNode(org.codehaus.groovy.ast.InterfaceHelperClassNode) PackageNode(org.codehaus.groovy.ast.PackageNode) MopWriter(org.codehaus.groovy.classgen.asm.MopWriter) WriterControllerFactory(org.codehaus.groovy.classgen.asm.WriterControllerFactory)

Example 53 with GroovyRuntimeException

use of groovy.lang.GroovyRuntimeException 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 54 with GroovyRuntimeException

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

the class ProxyGeneratorAdapter method proxy.

@SuppressWarnings("unchecked")
public GroovyObject proxy(Map<Object, Object> map, Object... constructorArgs) {
    if (constructorArgs == null && cachedNoArgConstructor != null) {
        // if there isn't any argument, we can make invocation faster using the cached constructor
        try {
            return (GroovyObject) cachedNoArgConstructor.newInstance(map);
        } catch (InstantiationException e) {
            throw new GroovyRuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new GroovyRuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new GroovyRuntimeException(e);
        }
    }
    if (constructorArgs == null)
        constructorArgs = EMPTY_ARGS;
    Object[] values = new Object[constructorArgs.length + 1];
    System.arraycopy(constructorArgs, 0, values, 0, constructorArgs.length);
    values[values.length - 1] = map;
    return DefaultGroovyMethods.<GroovyObject>newInstance(cachedClass, values);
}
Also used : GroovyRuntimeException(groovy.lang.GroovyRuntimeException) GroovyObject(groovy.lang.GroovyObject) InvocationTargetException(java.lang.reflect.InvocationTargetException) GroovyObject(groovy.lang.GroovyObject)

Example 55 with GroovyRuntimeException

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

the class MixinInMetaClass method mixinClassesToMetaClass.

public static void mixinClassesToMetaClass(MetaClass self, List<Class> categoryClasses) {
    final Class selfClass = self.getTheClass();
    if (self instanceof HandleMetaClass) {
        self = (MetaClass) ((HandleMetaClass) self).replaceDelegate();
    }
    if (!(self instanceof ExpandoMetaClass)) {
        if (self instanceof DelegatingMetaClass && ((DelegatingMetaClass) self).getAdaptee() instanceof ExpandoMetaClass) {
            self = ((DelegatingMetaClass) self).getAdaptee();
        } else {
            throw new GroovyRuntimeException("Can't mixin methods to meta class: " + self);
        }
    }
    ExpandoMetaClass mc = (ExpandoMetaClass) self;
    List<MetaMethod> arr = new ArrayList<MetaMethod>();
    for (Class categoryClass : categoryClasses) {
        final CachedClass cachedCategoryClass = ReflectionCache.getCachedClass(categoryClass);
        final MixinInMetaClass mixin = new MixinInMetaClass(mc, cachedCategoryClass);
        final MetaClass metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(categoryClass);
        final List<MetaProperty> propList = metaClass.getProperties();
        for (MetaProperty prop : propList) if (self.getMetaProperty(prop.getName()) == null) {
            mc.registerBeanProperty(prop.getName(), new MixinInstanceMetaProperty(prop, mixin));
        }
        for (MetaProperty prop : cachedCategoryClass.getFields()) if (self.getMetaProperty(prop.getName()) == null) {
            mc.registerBeanProperty(prop.getName(), new MixinInstanceMetaProperty(prop, mixin));
        }
        for (MetaMethod method : metaClass.getMethods()) {
            final int mod = method.getModifiers();
            if (!Modifier.isPublic(mod))
                continue;
            if (method instanceof CachedMethod && ((CachedMethod) method).getCachedMethod().isSynthetic())
                continue;
            if (Modifier.isStatic(mod)) {
                if (method instanceof CachedMethod)
                    staticMethod(self, arr, (CachedMethod) method);
            } else if (method.getDeclaringClass().getTheClass() != Object.class || method.getName().equals("toString")) {
                //                    if (self.pickMethod(method.getName(), method.getNativeParameterTypes()) == null) {
                final MixinInstanceMetaMethod metaMethod = new MixinInstanceMetaMethod(method, mixin);
                arr.add(metaMethod);
            //                    }
            }
        }
    }
    for (Object res : arr) {
        final MetaMethod metaMethod = (MetaMethod) res;
        if (metaMethod.getDeclaringClass().isAssignableFrom(selfClass))
            mc.registerInstanceMethod(metaMethod);
        else {
            mc.registerSubclassInstanceMethod(metaMethod);
        }
    }
}
Also used : MixinInstanceMetaMethod(org.codehaus.groovy.runtime.metaclass.MixinInstanceMetaMethod) MetaMethod(groovy.lang.MetaMethod) NewInstanceMetaMethod(org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod) HandleMetaClass(org.codehaus.groovy.runtime.HandleMetaClass) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) ArrayList(java.util.ArrayList) MetaClass(groovy.lang.MetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass) MixedInMetaClass(org.codehaus.groovy.runtime.metaclass.MixedInMetaClass) HandleMetaClass(org.codehaus.groovy.runtime.HandleMetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) MixinInstanceMetaProperty(org.codehaus.groovy.runtime.metaclass.MixinInstanceMetaProperty) MetaClass(groovy.lang.MetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass) MixedInMetaClass(org.codehaus.groovy.runtime.metaclass.MixedInMetaClass) HandleMetaClass(org.codehaus.groovy.runtime.HandleMetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass) MixinInstanceMetaProperty(org.codehaus.groovy.runtime.metaclass.MixinInstanceMetaProperty) MetaProperty(groovy.lang.MetaProperty) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) MixinInstanceMetaMethod(org.codehaus.groovy.runtime.metaclass.MixinInstanceMetaMethod)

Aggregations

GroovyRuntimeException (groovy.lang.GroovyRuntimeException)59 IOException (java.io.IOException)15 InvocationTargetException (java.lang.reflect.InvocationTargetException)9 GroovyObject (groovy.lang.GroovyObject)8 ArrayList (java.util.ArrayList)6 Closure (groovy.lang.Closure)5 InputStream (java.io.InputStream)5 List (java.util.List)5 GroovyShell (groovy.lang.GroovyShell)4 MetaClass (groovy.lang.MetaClass)4 Map (java.util.Map)4 ClassNode (org.codehaus.groovy.ast.ClassNode)4 MethodNode (org.codehaus.groovy.ast.MethodNode)4 MetaMethod (groovy.lang.MetaMethod)3 Script (groovy.lang.Script)3 PrintWriter (java.io.PrintWriter)3 StringWriter (java.io.StringWriter)3 URL (java.net.URL)3 DelegatingMetaClass (groovy.lang.DelegatingMetaClass)2 ExpandoMetaClass (groovy.lang.ExpandoMetaClass)2