Java Code Examples for groovy.lang.GroovyRuntimeException

The following examples show how to use groovy.lang.GroovyRuntimeException. These examples are extracted from open source projects. 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
@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 2
Source Project: groovy   Source File: NumberAwareComparator.java    License: 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 3
Source Project: groovy   Source File: ProcessGroovyMethods.java    License: 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 4
Source Project: groovy   Source File: GroovyAssert.java    License: 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 5
Source Project: groovy   Source File: GroovyAssert.java    License: 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 6
Source Project: groovy   Source File: DataSet.java    License: 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 7
Source Project: groovy   Source File: JUnit5Runner.java    License: 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 8
Source Project: groovy   Source File: AsmDecompiler.java    License: 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 9
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 10
Source Project: groovy   Source File: GroovyAssert.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the given code closure fails when it is evaluated
 * and that a particular Exception type can be attributed to the cause.
 * The expected exception class is compared recursively with any nested
 * exceptions using getCause() until either a match is found or no more
 * nested exceptions exist.
 * <p>
 * If a match is found, the matching exception is returned
 * otherwise the method will fail.
 *
 * @param expectedCause the class of the expected exception
 * @param code          the closure that should fail
 * @return the cause
 */
public static Throwable shouldFailWithCause(Class expectedCause, Closure code) {
    if (expectedCause == null) {
        fail("The expectedCause class cannot be null");
    }
    Throwable cause = null;
    Throwable orig = null;
    int level = 0;
    try {
        code.call();
    } catch (GroovyRuntimeException gre) {
        orig = ScriptBytecodeAdapter.unwrap(gre);
        cause = orig.getCause();
    } catch (Throwable e) {
        orig = e;
        cause = orig.getCause();
    }

    if (orig != null && cause == null) {
        fail("Closure " + code + " was expected to fail due to a nested cause of type " + expectedCause.getName() +
        " but instead got a direct exception of type " + orig.getClass().getName() + " with no nested cause(s). Code under test has a bug or perhaps you meant shouldFail?");
    }

    while (cause != null && !expectedCause.isInstance(cause) && cause != cause.getCause() && level < MAX_NESTED_EXCEPTIONS) {
        cause = cause.getCause();
        level++;
    }

    if (orig == null) {
        fail("Closure " + code + " should have failed with an exception having a nested cause of type " + expectedCause.getName());
    } else if (cause == null || !expectedCause.isInstance(cause)) {
        fail("Closure " + code + " should have failed with an exception having a nested cause of type " + expectedCause.getName() + ", instead found these Exceptions:\n" + buildExceptionList(orig));
    }
    return cause;
}
 
Example 11
Source Project: AlgoTrader   Source File: GrailsDataBinder.java    License: GNU General Public License v2.0 5 votes vote down vote up
private Object autoInstantiateDomainInstance(Class<?> type) {
	Object created = null;
	try {
		MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(type);
		if (mc != null) {
			created = mc.invokeStaticMethod(type, CreateDynamicMethod.METHOD_NAME, new Object[0]);
		}
	} catch (MissingMethodException mme) {
		LOG.warn("Unable to auto-create type, 'create' method not found");
	} catch (GroovyRuntimeException gre) {
		LOG.warn("Unable to auto-create type, Groovy Runtime error: " + gre.getMessage(), gre);
	}
	return created;
}
 
Example 12
Source Project: groovy   Source File: StringGroovyMethods.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Same logic as {@link #stripIndent(CharSequence)} if {@code forceGroovyBehavior} is {@code true},
 * otherwise Java 13's {@code stripIndent} will be invoked.
 *
 * @param self The CharSequence to strip the leading spaces from
 * @param forceGroovyBehavior force groovy behavior to avoid conflicts with Java13's stripIndent
 *
 * @since 3.0.0
 */
@Incubating
public static String stripIndent(final CharSequence self, final boolean forceGroovyBehavior) {
    if (!forceGroovyBehavior) {
        try {
            MethodHandle mh = MethodHandles.lookup().findVirtual(self.getClass(), "stripIndent", MethodType.methodType(String.class));
            return (String) mh.bindTo(self).invokeWithArguments();
        } catch (NoSuchMethodException | IllegalAccessException ignored) {
        } catch (Throwable t) {
            throw new GroovyRuntimeException(t);
        }
    }

    return stripIndent(self);
}
 
Example 13
Source Project: groovy   Source File: InvokerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testInvokerException() throws Throwable {
    try {
        throw new GroovyRuntimeException("message", new NullPointerException());
    }
    catch (GroovyRuntimeException e) {
        // worked
        assertEquals("message", e.getMessage());
        assertTrue(e.getCause() instanceof NullPointerException);
    }
}
 
Example 14
Source Project: groovy   Source File: Selector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds the standard exception handler.
 */
public void addExceptionHandler() {
    //TODO: if we would know exactly which paths require the exceptions
    //      and which paths not, we can sometimes save this guard 
    if (handle == null || !catchException) return;
    Class<?> returnType = handle.type().returnType();
    if (returnType != Object.class) {
        MethodType mtype = MethodType.methodType(returnType, GroovyRuntimeException.class);
        handle = MethodHandles.catchException(handle, GroovyRuntimeException.class, UNWRAP_EXCEPTION.asType(mtype));
    } else {
        handle = MethodHandles.catchException(handle, GroovyRuntimeException.class, UNWRAP_EXCEPTION);
    }
    if (LOG_ENABLED) LOG.info("added GroovyRuntimeException unwrapper");
}
 
Example 15
Source Project: groovy   Source File: DOMCategory.java    License: Apache License 2.0 5 votes vote down vote up
public static Node replaceNode(NodesHolder self, Closure c) {
    if (self.getLength() != 1) {
        throw new GroovyRuntimeException(
                "replaceNode() can only be used to replace a single element, " +
                "but was applied to " + self.getLength() + " elements."
        );
    }
    return replaceNode(self.item(0), c);
}
 
Example 16
Source Project: groovy   Source File: SqlExtensions.java    License: Apache License 2.0 5 votes vote down vote up
public boolean hasNext() {
    try {
        return index <= target.getColumnCount();
    }
    catch (SQLException ex) {
        throw new GroovyRuntimeException("Unable to obtain column count from ResultSetMetaData", ex);
    }
}
 
Example 17
Source Project: groovy   Source File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static Object getGroovyObjectField(Class senderClass, GroovyObject receiver, String messageName) throws Throwable {
    try  {
        return receiver.getMetaClass().getAttribute(receiver, messageName);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
 
Example 18
Source Project: groovy   Source File: ConstructorSite.java    License: Apache License 2.0 5 votes vote down vote up
public final Object callConstructor(Object receiver, Object[] args) throws Throwable {
    if (checkCall(receiver, args)) {
        try {
            return constructor.doConstructorInvoke(args);
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    } else
        return CallSiteArray.defaultCallConstructor(this, receiver, args);
}
 
Example 19
Source Project: groovy   Source File: DateTimeExtensions.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the {@code from} can be iterated up to {@code to}.
 */
private static boolean isUptoEligible(Temporal from, Temporal to) {
    TemporalAmount amount = rightShift(from, to);
    if (amount instanceof Period) {
        return isNonnegative((Period) amount);
    } else if (amount instanceof Duration) {
        return isNonnegative((Duration) amount);
    } else {
        throw new GroovyRuntimeException("Temporal implementations of "
                + from.getClass().getCanonicalName() + " are not supported by upto().");
    }
}
 
Example 20
Source Project: groovy   Source File: PogoGetPropertySite.java    License: Apache License 2.0 5 votes vote down vote up
public Object getProperty(Object receiver) throws Throwable {
    try{
        return ((GroovyObject)receiver).getProperty(name);
    } catch (GroovyRuntimeException gre) {
        throw ScriptBytecodeAdapter.unwrap(gre);
    }
}
 
Example 21
Source Project: groovy   Source File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static void setGroovyObjectField(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable {
    try {
        receiver.getMetaClass().setAttribute(receiver, messageName, messageArgument);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
 
Example 22
Source Project: groovy   Source File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static int selectConstructorAndTransformArguments(Object[] arguments, int numberOfConstructors, Class which) throws Throwable {
    MetaClass metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(which);
    try {
        return metaClass.selectConstructorAndTransformArguments(numberOfConstructors, arguments);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
 
Example 23
Source Project: groovy   Source File: ConstructorSite.java    License: Apache License 2.0 5 votes vote down vote up
public Object callConstructor(Object receiver, Object[] args) throws Throwable {
    if (checkCall(receiver, args)) {
        MetaClassHelper.unwrap(args);
        try {
            return constructor.doConstructorInvoke(args);
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    } else
        return CallSiteArray.defaultCallConstructor(this, receiver, args);
}
 
Example 24
Source Project: groovy   Source File: ProcessGroovyMethods.java    License: Apache License 2.0 5 votes vote down vote up
public void run() {
    byte[] buf = new byte[8192];
    int next;
    try {
        while ((next = in.read(buf)) != -1) {
            if (out != null) out.write(buf, 0, next);
        }
    } catch (IOException e) {
        throw new GroovyRuntimeException("exception while dumping process stream", e);
    }
}
 
Example 25
Source Project: groovy   Source File: DateUtilExtensions.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Iterates from the date represented by this calendar up to the date represented
 * by the given calendar, inclusive, incrementing by one day each time.
 *
 * @param self    a Calendar
 * @param to      another Calendar to go down to
 * @param closure the closure to call
 * @since 2.2
 */
public static void downto(Calendar self, Calendar to, Closure closure) {
    if (self.compareTo(to) >= 0) {
        for (Calendar i = (Calendar) self.clone(); i.compareTo(to) >= 0; i = previous(i)) {
            closure.call(i);
        }
    } else
        throw new GroovyRuntimeException("The argument (" + to +
                ") to downto() cannot be later than the value (" + self + ") it's called on.");
}
 
Example 26
Source Project: groovy   Source File: DefaultRunners.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Run the specified class extending TestCase as a unit test.
 * This is done through reflection, to avoid adding a dependency to the JUnit framework.
 * Otherwise, developers embedding Groovy and using GroovyShell to load/parse/compile
 * groovy scripts and classes would have to add another dependency on their classpath.
 *
 * @param scriptClass the class to be run as a unit test
 * @param loader the class loader
 */
@Override
public Object run(Class<?> scriptClass, GroovyClassLoader loader) {
    try {
        Object testSuite = InvokerHelper.invokeConstructorOf("junit.framework.TestSuite", new Object[]{scriptClass});
        return InvokerHelper.invokeStaticMethod("junit.textui.TestRunner", "run", new Object[]{testSuite});
    } catch (ClassNotFoundException e) {
        throw new GroovyRuntimeException("Failed to run the unit test. JUnit is not on the Classpath.", e);
    }
}
 
Example 27
Source Project: groovy   Source File: InvokeMethodTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testInvalidOverloading() throws Throwable {
    try {
        invoke(this, "badOverload", new Object[]{"a", "b"});
        fail("Should fail as an unambiguous method is invoked");
    }
    catch (GroovyRuntimeException e) {
        System.out.println("Caught: " + e);
    }
}
 
Example 28
Source Project: groovy   Source File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static Object getGroovyObjectFieldSafe(Class senderClass, GroovyObject receiver, String messageName) throws Throwable {
    if (receiver == null) return null;
    try {
        return receiver.getMetaClass().getAttribute(receiver, messageName);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
 
Example 29
Source Project: groovy   Source File: ScriptRunner.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Run the script file specified by the file path
 *
 * @param path the file
 * @since 3.0.0
 */
public static void runScript(File path) {
    try {
        GroovyStarter.main(new String[] {"--main", "groovy.ui.GroovyMain", path.getCanonicalPath()});
    } catch (IOException e) {
        throw new GroovyRuntimeException("Failed to run script: " + path, e);
    }
}
 
Example 30
Source Project: groovy   Source File: GetEffectivePogoPropertySite.java    License: Apache License 2.0 5 votes vote down vote up
public final Object callGetProperty (Object receiver) throws Throwable {
    if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject) receiver).getMetaClass() != metaClass) {
        return createGetPropertySite(receiver).getProperty(receiver);
    } else {
        try {
            return effective.getProperty(receiver);
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    }
}