groovy.lang.GroovyRuntimeException Java Examples

The following examples show how to use groovy.lang.GroovyRuntimeException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AsmDecompiler.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the URL contents and parses them with ASM, producing a {@link ClassStub} object representing the structure of
 * the corresponding class file. Stubs are cached and reused if queried several times with equal URLs.
 *
 * @param url an URL from a class loader, most likely a file system file or a JAR entry.
 * @return the class stub
 * @throws IOException if reading from this URL is impossible
 */
public static ClassStub parseClass(URL url) throws IOException {
    URI uri;
    try {
        uri = url.toURI();
    } catch (URISyntaxException e) {
        throw new GroovyRuntimeException(e);
    }

    SoftReference<ClassStub> ref = StubCache.map.get(uri);
    ClassStub stub = ref == null ? null : ref.get();
    if (stub == null) {
        DecompilingVisitor visitor = new DecompilingVisitor();

        try (InputStream stream = new BufferedInputStream(URLStreams.openUncachedStream(url))) {
            new ClassReader(stream).accept(visitor, ClassReader.SKIP_FRAMES);
        }
        stub = visitor.result;
        StubCache.map.put(uri, new SoftReference<ClassStub>(stub));
    }
    return stub;
}
 
Example #2
Source File: JUnit5Runner.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to run a JUnit 5 test.
 *
 * @param scriptClass the class we want to run as a test
 * @param loader the class loader to use
 * @return the result of running the test
 */
@Override
public Object run(Class<?> scriptClass, GroovyClassLoader loader) {
    try {
        try {
            loader.loadClass("org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder");
        } catch (ClassNotFoundException ignored) {
            // subsequent steps will bomb out but try to give some more friendly information first
            System.err.println("WARNING: Required dependency: org.junit.platform:junit-platform-launcher doesn't appear to be on the classpath");
        }
        Class<?> helper = loader.loadClass("groovy.junit5.plugin.GroovyJUnitRunnerHelper");
        Throwable ifFailed = (Throwable) InvokerHelper.invokeStaticMethod(helper, "execute", new Object[]{scriptClass});
        if (ifFailed != null) {
            throw new GroovyRuntimeException(ifFailed);
        }
        return null;
    } catch (ClassNotFoundException e) {
        throw new GroovyRuntimeException("Error running JUnit 5 test.", e);
    }
}
 
Example #3
Source File: DataSet.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void visit(Closure closure, CodeVisitorSupport visitor) {
    if (closure != null) {
        ClassNode classNode = closure.getMetaClass().getClassNode();
        if (classNode == null) {
            throw new GroovyRuntimeException(
                    "DataSet unable to evaluate expression. AST not available for closure: " + closure.getMetaClass().getTheClass().getName() +
                            ". Is the source code on the classpath?");
        }
        List methods = classNode.getDeclaredMethods("doCall");
        if (!methods.isEmpty()) {
            MethodNode method = (MethodNode) methods.get(0);
            if (method != null) {
                Statement statement = method.getCode();
                if (statement != null) {
                    statement.visit(visitor);
                }
            }
        }
    }
}
 
Example #4
Source File: GroovyAssert.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the given script fails when it is evaluated
 * and that a particular type of exception is thrown.
 *
 * @param clazz the class of the expected exception
 * @param script  the script that should fail
 * @return the caught exception
 */
public static Throwable shouldFail(Class clazz, String script) {
    Throwable th = null;
    try {
        GroovyShell shell = new GroovyShell();
        shell.evaluate(script, genericScriptName());
    } catch (GroovyRuntimeException gre) {
        th = ScriptBytecodeAdapter.unwrap(gre);
    } catch (Throwable e) {
        th = e;
    }

    if (th == null) {
        fail("Script should have failed with an exception of type " + clazz.getName());
    } else if (!clazz.isInstance(th)) {
        fail("Script should have failed with an exception of type " + clazz.getName() + ", instead got Exception " + th);
    }
    return th;
}
 
Example #5
Source File: GroovyEvaluator.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected Object handleEvaluationException(JRExpression expression, Throwable e) throws JRExpressionEvalException
{
	if (ignoreNPE && e instanceof GroovyRuntimeException && e.getMessage() != null)
	{
		//in Groovy 2.0.1, 1 + null (and other e.g. BigDecimal * null) was throwing NPE
		//in 2.4.3, it fails with "Ambiguous method overloading..."
		//we're catching this exception (by message) and treating it like a NPE
		Matcher matcher = GROOVY_EXCEPTION_PATTERN_AMBIGUOUS_NULL.matcher(e.getMessage());
		if (matcher.matches())
		{
			//evaluating the expression to null to match Groovy 2.0.1 behaviour
			return null;
		}
	}
	
	//throw the exception
	return super.handleEvaluationException(expression, e);
}
 
Example #6
Source File: GroovyAssert.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the given code closure fails when it is evaluated
 *
 * @param code the code expected to fail
 * @return the caught exception
 */
public static Throwable shouldFail(Closure code) {
    boolean failed = false;
    Throwable th = null;
    try {
        code.call();
    } catch (GroovyRuntimeException gre) {
        failed = true;
        th = ScriptBytecodeAdapter.unwrap(gre);
    } catch (Throwable e) {
        failed = true;
        th = e;
    }
    assertTrue("Closure " + code + " should have failed", failed);
    return th;
}
 
Example #7
Source File: ProcessGroovyMethods.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Allows one Process to asynchronously pipe data to another Process.
 *
 * @param left  a Process instance
 * @param right a Process to pipe output to
 * @return the second Process to allow chaining
 * @throws java.io.IOException if an IOException occurs.
 * @since 1.5.2
 */
public static Process pipeTo(final Process left, final Process right) throws IOException {
    new Thread(() -> {
        InputStream in = new BufferedInputStream(getIn(left));
        OutputStream out = new BufferedOutputStream(getOut(right));
        byte[] buf = new byte[8192];
        int next;
        try {
            while ((next = in.read(buf)) != -1) {
                out.write(buf, 0, next);
            }
        } catch (IOException e) {
            throw new GroovyRuntimeException("exception while reading process stream", e);
        } finally {
            closeWithWarning(out);
            closeWithWarning(in);
        }
    }).start();
    return right;
}
 
Example #8
Source File: NumberAwareComparator.java    From groovy with Apache License 2.0 6 votes vote down vote up
public int compare(T o1, T o2) {
    try {
        return DefaultTypeTransformation.compareTo(o1, o2);
    } catch (ClassCastException | IllegalArgumentException | GroovyRuntimeException cce) {
        /* ignore */
    }
    // since the object does not have a valid compareTo method
    // we compare using the hashcodes. null cases are handled by
    // DefaultTypeTransformation.compareTo
    // This is not exactly a mathematical valid approach, since we compare object
    // that cannot be compared. To avoid strange side effects we do a pseudo order
    // using hashcodes, but without equality. Since then an x and y with the same
    // hashcodes will behave different depending on if we compare x with y or
    // x with y, the result might be unstable as well. Setting x and y to equal
    // may mean the removal of x or y in a sorting operation, which we don't want.
    int x1 = o1.hashCode();
    int x2 = o2.hashCode();
    if (x1 == x2 && o1.equals(o2)) return 0;
    if (x1 > x2) return 1;
    return -1;
}
 
Example #9
Source File: PojoMetaClassGetPropertySite.java    From groovy with Apache License 2.0 5 votes vote down vote up
public final Object getProperty(Object receiver) throws Throwable {
    try {
        return InvokerHelper.getProperty(receiver, name);
    } catch (GroovyRuntimeException gre) {
        throw ScriptBytecodeAdapter.unwrap(gre);
    }
}
 
Example #10
Source File: MetaClassConstructorSite.java    From groovy with Apache License 2.0 5 votes vote down vote up
public Object callConstructor(Object receiver, Object[] args) throws Throwable {
    try {
        if (receiver == metaClass.getTheClass()
            && version == classInfo.getVersion()) // metaClass still be valid
            return metaClass.invokeConstructor(args);
        else
          return CallSiteArray.defaultCallConstructor(this, receiver, args);
    } catch (GroovyRuntimeException gre) {
        throw ScriptBytecodeAdapter.unwrap(gre);
    }
}
 
Example #11
Source File: ProcessGroovyMethods.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void run() {
    InputStreamReader isr = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(isr);
    String next;
    try {
        while ((next = br.readLine()) != null) {
            if (app != null) {
                app.append(next);
                app.append("\n");
            }
        }
    } catch (IOException e) {
        throw new GroovyRuntimeException("exception while reading process stream", e);
    }
}
 
Example #12
Source File: GetEffectivePojoPropertySite.java    From groovy with Apache License 2.0 5 votes vote down vote up
public final Object getProperty(Object receiver) throws Throwable {
    try {
        return effective.getProperty(receiver);
    } catch (GroovyRuntimeException gre) {
        throw ScriptBytecodeAdapter.unwrap(gre);
    }
}
 
Example #13
Source File: PogoMetaClassGetPropertySite.java    From groovy with Apache License 2.0 5 votes vote down vote up
public final Object getProperty(Object receiver) throws Throwable {
    try {
        return metaClass.getProperty(receiver, name);
    } catch (GroovyRuntimeException gre) {
        throw ScriptBytecodeAdapter.unwrap(gre);
    }
}
 
Example #14
Source File: PerInstancePojoMetaClassSite.java    From groovy with Apache License 2.0 5 votes vote down vote up
public Object call(Object receiver, Object[] args) throws Throwable {
    if (receiver != null && info.hasPerInstanceMetaClasses()) {
        try {
            return InvokerHelper.getMetaClass(receiver).invokeMethod(receiver, name, args);
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    } else {
        return CallSiteArray.defaultCall(this, receiver, args);
    }
}
 
Example #15
Source File: StaticMetaClassSite.java    From groovy with Apache License 2.0 5 votes vote down vote up
public final Object call(Object receiver, Object[] args) throws Throwable {
    if (checkCall(receiver)) {
        try {
            return metaClass.invokeStaticMethod(receiver, name, args);
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    } else {
        return CallSiteArray.defaultCall(this, receiver, args);
    }
}
 
Example #16
Source File: ScriptBytecodeAdapter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static void setPropertyOnSuper(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable {
    try {
        InvokerHelper.setAttribute(receiver, messageName, messageArgument);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
 
Example #17
Source File: StaticMetaClassSite.java    From groovy with Apache License 2.0 5 votes vote down vote up
public final Object callStatic(Class receiver, Object[] args) throws Throwable {
    if (checkCall(receiver)) {
        try {
            return metaClass.invokeStaticMethod(receiver, name, args);
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    } else {
        return CallSiteArray.defaultCallStatic(this, receiver, args);
    }
}
 
Example #18
Source File: PogoMetaMethodSite.java    From groovy with Apache License 2.0 5 votes vote down vote up
public final Object invoke(Object receiver, Object[] args) throws Throwable {
    try {
        return metaMethod.invoke(receiver,  args);
    } catch (GroovyRuntimeException gre) {
        throw ScriptBytecodeAdapter.unwrap(gre);
    }
}
 
Example #19
Source File: ErrorReporter.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the report once all initialization is complete.
 */
protected void dispatch(Throwable object, boolean child) {
    if (object instanceof CompilationFailedException) {
        report((CompilationFailedException) object, child);
    } else if (object instanceof GroovyExceptionInterface) {
        report((GroovyExceptionInterface) object, child);
    } else if (object instanceof GroovyRuntimeException) {
        report((GroovyRuntimeException) object, child);
    } else if (object instanceof Exception) {
        report((Exception) object, child);
    } else {
        report(object, child);
    }

}
 
Example #20
Source File: PogoInterceptableSite.java    From groovy with Apache License 2.0 5 votes vote down vote up
public final Object invoke(Object receiver, Object[] args) throws Throwable {
  try {
    return ((GroovyObject)receiver).invokeMethod(name, InvokerHelper.asUnwrappedArray(args));
  } catch (GroovyRuntimeException gre) {
      throw ScriptBytecodeAdapter.unwrap(gre);
  }
}
 
Example #21
Source File: ScriptBytecodeAdapter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static void setGroovyObjectFieldSafe(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable {
    if (receiver == null) return;
    try {
        receiver.getMetaClass().setAttribute(receiver, messageName, messageArgument);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
 
Example #22
Source File: GroovyConsoleState.java    From Lemur with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void resetScriptEngine() {
    
    ScriptEngineManager factory = new ScriptEngineManager();        
    this.engine = factory.getEngineByName("groovy");
    globalBindings = engine.createBindings();
    engine.setBindings(globalBindings, ScriptContext.ENGINE_SCOPE); 
 
    // Clear the old imports
    imports.clear();
    importString = null;
 
    // Provide direct access to the bindings as a binding.
    // This can be useful for debugging 'not found' errors
    // inside scripts.
    globalBindings.put( "bindings", globalBindings );
    
    // Put all of the caller provided preset bindings
    globalBindings.putAll(initialBindings);
    
    // Run the API Scripts
    for( Map.Entry<Object, String> e : initScripts.entrySet() ) {
        try {
            String script = e.getValue();
            script = getImportString() + script;
            engine.eval(script); 
        } catch( ScriptException ex ) {
            throw new GroovyRuntimeException("Error executing initialization script:" + e.getKey(), ex);
        }
    }                           
}
 
Example #23
Source File: ConfigObject.java    From groovy with Apache License 2.0 5 votes vote down vote up
public String prettyPrint() {
    Writer sw = new StringBuilderWriter();
    try {
        writeTo(sw);
    } catch (IOException e) {
        throw new GroovyRuntimeException(e);
    }

    return sw.toString();
}
 
Example #24
Source File: CachedField.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the property on the given object to the new value
 *
 * @param object on which to set the property
 * @param newValue the new value of the property
 * @throws RuntimeException if the property could not be set
 */
public void setProperty(final Object object, Object newValue) {
    makeAccessibleIfNecessary();
    AccessPermissionChecker.checkAccessPermission(cachedField);
    final Object goalValue = DefaultTypeTransformation.castToType(newValue, cachedField.getType());

    if (isFinal()) {
        throw new GroovyRuntimeException("Cannot set the property '" + name + "' because the backing field is final.");
    }
    try {
        cachedField.set(object, goalValue);
    } catch (IllegalAccessException ex) {
        throw new GroovyRuntimeException("Cannot set the property '" + name + "'.", ex);
    }
}
 
Example #25
Source File: InvokeMethodTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testInvokeUnknownMethod() throws Throwable {
    try {
        Object value = invoke(this, "unknownMethod", "abc");
        fail("Should have thrown an exception");
    }
    catch (GroovyRuntimeException e) {
        // worked
    }
}
 
Example #26
Source File: GeneratedMetaMethod.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void createProxy() {
    try {
        Class<?> aClass = getClass().getClassLoader().loadClass(className.replace('/', '.'));
        Constructor<?> constructor = aClass.getConstructor(String.class, CachedClass.class, Class.class, Class[].class);
        proxy = (MetaMethod) constructor.newInstance(getName(), getDeclaringClass(), getReturnType(), getNativeParameterTypes());
    } catch (Throwable t) {
        t.printStackTrace();
        throw new GroovyRuntimeException("Failed to create DGM method proxy : " + t, t);
    }
}
 
Example #27
Source File: IndentPrinter.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Prints a string.
 *
 * @param  text String to be written
 */
public void print(String text) {
    try {
        out.write(text);
    } catch(IOException ioe) {
        throw new GroovyRuntimeException(ioe);
    }
}
 
Example #28
Source File: CachedClass.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void setNewMopMethods(List<MetaMethod> arr) {
    final MetaClass metaClass = classInfo.getStrongMetaClass();
    if (metaClass != null) {
      if (metaClass.getClass() == MetaClassImpl.class) {
          classInfo.setStrongMetaClass(null);
          updateSetNewMopMethods(arr);
          MetaClassImpl mci = new MetaClassImpl(metaClass.getTheClass());
          mci.initialize();
          classInfo.setStrongMetaClass(mci);
          return;
      }

      if (metaClass.getClass() == ExpandoMetaClass.class) {
          classInfo.setStrongMetaClass(null);
          updateSetNewMopMethods(arr);
          ExpandoMetaClass newEmc = new ExpandoMetaClass(metaClass.getTheClass());
          newEmc.initialize();
          classInfo.setStrongMetaClass(newEmc);
          return;
      }

      throw new GroovyRuntimeException("Can't add methods to class " + getTheClass().getName() + ". Strong custom meta class already set.");
    }

    classInfo.setWeakMetaClass(null);
    updateSetNewMopMethods(arr);
}
 
Example #29
Source File: MixinInMetaClass.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static CachedConstructor findDefaultConstructor(CachedClass mixinClass) {
    for (CachedConstructor constr : mixinClass.getConstructors()) {
        if (!Modifier.isPublic(constr.getModifiers()))
            continue;

        CachedClass[] classes = constr.getParameterTypes();
        if (classes.length == 0)
            return constr;
    }

    throw new GroovyRuntimeException("No default constructor for class " + mixinClass.getName() + "! Can't be mixed in.");
}
 
Example #30
Source File: ScriptBytecodeAdapter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static Object invokeNewN(Class senderClass, Class receiver, Object arguments) throws Throwable {
    try {
        return InvokerHelper.invokeConstructorOf(receiver, arguments);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}