Java 类groovy.lang.GroovyRuntimeException 实例源码

项目:jasperreports    文件:GroovyEvaluator.java   
@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);
}
项目:intellij-ce-playground    文件:GroovyCompilerWrapper.java   
private void processException(Throwable exception, String prefix) {
  if (exception instanceof GroovyRuntimeException) {
    addErrorMessage((GroovyRuntimeException) exception);
    return;
  }

  if (forStubs) {
    collector.add(new CompilerMessage(GroovyCompilerMessageCategories.INFORMATION,
                                      GroovyRtConstants.GROOVYC_STUB_GENERATION_FAILED, null, -1, -1));
  }

  final StringWriter writer = new StringWriter();
  writer.append(prefix);
  if (!prefix.endsWith("\n")) {
    writer.append("\n\n");
  }
  //noinspection IOResourceOpenedButNotSafelyClosed
  exception.printStackTrace(new PrintWriter(writer));
  collector.add(new CompilerMessage(forStubs ? GroovyCompilerMessageCategories.INFORMATION : GroovyCompilerMessageCategories.ERROR, writer.toString(), null, -1, -1));
}
项目:groovy    文件:GroovyTest.java   
private void testFileNameInStackTrace(final String target, final String fileNamePattern) {
    try {
        project.executeTarget(target);
        fail();
    }
    catch (final BuildException e) {
        assertEquals(BuildException.class, e.getClass());
        final Throwable cause = e.getCause();
        assertTrue(cause instanceof GroovyRuntimeException);

        final Writer sw = new StringBuilderWriter();
        cause.printStackTrace(new PrintWriter(sw));

        final String stackTrace = sw.toString();
        final Pattern pattern = Pattern.compile(fileNamePattern);
        assertTrue("Does >" + stackTrace + "< contain >" + fileNamePattern + "<?", 
                pattern.matcher(stackTrace).find());
    }
}
项目:groovy    文件:GroovyAssert.java   
/**
 * Asserts that the given code closure fails when it is evaluated
 *
 * @param code the code expected to throw the exception
 * @return the message of the thrown Throwable
 */
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;
}
项目:groovy    文件:GroovyAssert.java   
/**
 * 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;
}
项目:groovy    文件:GroovyAssert.java   
/**
 * 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;
}
项目:groovy    文件:DataSet.java   
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);
                }
            }
        }
    }
}
项目:groovy    文件:TestNgRunner.java   
/**
 * Utility method to run a TestNG 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 {
        Class<?> testNGClass = loader.loadClass("org.testng.TestNG");
        Object testng = InvokerHelper.invokeConstructorOf(testNGClass, new Object[]{});
        InvokerHelper.invokeMethod(testng, "setTestClasses", new Object[]{scriptClass});
        Class<?> listenerClass = loader.loadClass("org.testng.TestListenerAdapter");
        Object listener = InvokerHelper.invokeConstructorOf(listenerClass, new Object[]{});
        InvokerHelper.invokeMethod(testng, "addListener", new Object[]{listener});
        if (OUTPUT_DIRECTORY != null) {
            InvokerHelper.invokeMethod(testng, "setOutputDirectory", new Object[]{OUTPUT_DIRECTORY});
        }
        return InvokerHelper.invokeMethod(testng, "run", new Object[]{});
    } catch (ClassNotFoundException e) {
        throw new GroovyRuntimeException("Error running TestNG test.", e);
    }
}
项目:groovy    文件:DefaultRunners.java   
/**
 * 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 {
        Class<?> junitCoreClass = loader.loadClass("org.junit.runner.JUnitCore");
        Object result = InvokerHelper.invokeStaticMethod(junitCoreClass,
                "runClasses", new Object[]{scriptClass});
        System.out.print("JUnit 4 Runner, Tests: " + InvokerHelper.getProperty(result, "runCount"));
        System.out.print(", Failures: " + InvokerHelper.getProperty(result, "failureCount"));
        System.out.println(", Time: " + InvokerHelper.getProperty(result, "runTime"));
        List<?> failures = (List<?>) InvokerHelper.getProperty(result, "failures");
        for (Object f : failures) {
            System.out.println("Test Failure: " + InvokerHelper.getProperty(f, "description"));
            System.out.println(InvokerHelper.getProperty(f, "trace"));
        }
        return result;
    } catch (ClassNotFoundException e) {
        throw new GroovyRuntimeException("Error running JUnit 4 test.", e);
    }
}
项目:groovy    文件:ErrorReporter.java   
/**
*  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 );
    }

}
项目:groovy    文件:AsmDecompiler.java   
/**
 * 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();
        InputStream stream = url.openStream();
        try {
            new ClassReader(new BufferedInputStream(stream)).accept(visitor, ClassReader.SKIP_FRAMES);
        } finally {
            stream.close();
        }
        stub = visitor.result;
        StubCache.map.put(uri, new SoftReference<ClassStub>(stub));
    }
    return stub;
}
项目:groovy    文件:JUnit4Utils.java   
/**
 * Utility method to run a JUnit4 test.
 *
 * @param scriptClass the class we want to run as a test
 * @return the result of running the test
 */
static Object realRunJUnit4Test(Class scriptClass, GroovyClassLoader loader) {
    // invoke through reflection to eliminate mandatory JUnit 4 jar dependency

    try {
        Class junitCoreClass = loader.loadClass("org.junit.runner.JUnitCore");
        Object result = InvokerHelper.invokeStaticMethod(junitCoreClass,
                "runClasses", new Object[]{scriptClass});
        System.out.print("JUnit 4 Runner, Tests: " + InvokerHelper.getProperty(result, "runCount"));
        System.out.print(", Failures: " + InvokerHelper.getProperty(result, "failureCount"));
        System.out.println(", Time: " + InvokerHelper.getProperty(result, "runTime"));
        List failures = (List) InvokerHelper.getProperty(result, "failures");
        for (int i = 0; i < failures.size(); i++) {
            Object f = failures.get(i);
            System.out.println("Test Failure: " + InvokerHelper.getProperty(f, "description"));
            System.out.println(InvokerHelper.getProperty(f, "trace"));
        }
        return result;
    } catch (ClassNotFoundException e) {
        throw new GroovyRuntimeException("Error running JUnit 4 test.", e);
    }
}
项目:groovy    文件:NumberAwareComparator.java   
public int compare(T o1, T o2) {
    try {
        return DefaultTypeTransformation.compareTo(o1, o2);
    } catch (ClassCastException cce) {
        /* ignore */
    } catch (GroovyRuntimeException gre) {
        /* ignore */
    } catch (IllegalArgumentException iae) {
        /* 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;
}
项目:groovy    文件:PogoMetaClassSite.java   
public final Object call(Object receiver, Object[] args) throws Throwable {
    if (checkCall(receiver)) {
        try {
            try {
                return metaClass.invokeMethod(receiver, name, args);
            } catch (MissingMethodException e) {
                if (e instanceof MissingMethodExecutionFailed) {
                    throw (MissingMethodException)e.getCause();
                } else if (receiver.getClass() == e.getType() && e.getMethod().equals(name)) {
                    // in case there's nothing else, invoke the object's own invokeMethod()
                    return ((GroovyObject)receiver).invokeMethod(name, args);
                } else {
                    throw e;
                }
            }
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    } else {
      return CallSiteArray.defaultCall(this, receiver, args);
    }
}
项目:groovy    文件:PogoMetaClassSite.java   
public final Object callCurrent(GroovyObject receiver, Object[] args) throws Throwable {
    if (checkCall(receiver)) {
        try {
            try {
                return metaClass.invokeMethod(array.owner, receiver, name, args, false, true);
            } catch (MissingMethodException e) {
                if (e instanceof MissingMethodExecutionFailed) {
                    throw (MissingMethodException)e.getCause();
                } else if (receiver.getClass() == e.getType() && e.getMethod().equals(name)) {
                    // in case there's nothing else, invoke the object's own invokeMethod()
                    return ((GroovyObject)receiver).invokeMethod(name, args);
                } else {
                    throw e;
                }
            }
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    } else {
      return CallSiteArray.defaultCallCurrent(this, receiver, args);
    }
}
项目:groovy    文件:DefaultGroovyMethods.java   
/**
 * Coerces this map to the given type, using the map's keys as the public
 * method names, and values as the implementation.  Typically the value
 * would be a closure which behaves like the method implementation.
 *
 * @param map   this map
 * @param clazz the target type
 * @return a Proxy of the given type, which defers calls to this map's elements.
 * @since 1.0
 */
@SuppressWarnings("unchecked")
public static <T> T asType(Map map, Class<T> clazz) {
    if (!(clazz.isInstance(map)) && clazz.isInterface() && !Traits.isTrait(clazz)) {
        return (T) Proxy.newProxyInstance(
                clazz.getClassLoader(),
                new Class[]{clazz},
                new ConvertedMap(map));
    }
    try {
        return asType((Object) map, clazz);
    } catch (GroovyCastException ce) {
        try {
            return (T) ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(map, clazz);
        } catch (GroovyRuntimeException cause) {
            throw new GroovyCastException("Error casting map to " + clazz.getName() +
                    ", Reason: " + cause.getMessage());
        }
    }
}
项目:Reer    文件:AbstractDynamicObject.java   
protected GroovyRuntimeException getWriteOnlyProperty(String name) {
    Class<?> publicType = getPublicType();
    boolean includeDisplayName = hasUsefulDisplayName();
    if (publicType != null && includeDisplayName) {
        return new GroovyRuntimeException(String.format(
                "Cannot get the value of write-only property '%s' for %s of type %s.", name, getDisplayName(), publicType.getName()));
    } else if (publicType != null) {
        return new GroovyRuntimeException(String.format(
                "Cannot get the value of write-only property '%s' for object of type %s.", name, publicType.getName()));
    } else {
        // Use the display name anyway
        return new GroovyRuntimeException(String.format(
                "Cannot get the value of write-only property '%s' for %s.", name, getDisplayName()));
    }
}
项目:Reer    文件:AbstractDynamicObject.java   
protected GroovyRuntimeException setReadOnlyProperty(String name) {
    Class<?> publicType = getPublicType();
    boolean includeDisplayName = hasUsefulDisplayName();
    if (publicType != null && includeDisplayName) {
        return new GroovyRuntimeException(String.format(
                "Cannot set the value of read-only property '%s' for %s of type %s.", name, getDisplayName(), publicType.getName()));
    } else if (publicType != null) {
        return new GroovyRuntimeException(String.format(
                "Cannot set the value of read-only property '%s' for object of type %s.", name, publicType.getName()));
    } else {
        // Use the display name anyway
        return new GroovyRuntimeException(String.format(
                "Cannot set the value of read-only property '%s' for %s.", name, getDisplayName()));
    }
}
项目:powsybl-core    文件:ScriptError.java   
public static ScriptError fromGroovyException(GroovyRuntimeException e, String scriptName) {
    Objects.requireNonNull(scriptName);
    for (StackTraceElement element : e.getStackTrace()) {
        if (scriptName.equals(element.getFileName())
                && scriptName.equals(element.getClassName())
                && "run".equals(element.getMethodName())) {
            return new ScriptError(e.getMessage(), element.getLineNumber(), -1, element.getLineNumber(), -1);
        }
    }
    return null;
}
项目:httpstub    文件:ExpressionCompiler.java   
/**
 * Compile a Groovy expression.
 * For example, {@code 1 + 1} will be {@code 2} on evaluated.
 * @param expression Groovy expression
 * @return compiled
 */
@SuppressWarnings("unchecked")
public CompiledExpression compileExpression(String expression, RouteSource source) {
    if (expression == null) {
        return null;
    }
    try {
        val clazz = new GroovyClassLoader().parseClass(expression, source.getName());
        return new CompiledExpression((Class<Script>) clazz);
    } catch (GroovyRuntimeException e) {
        throw new IllegalRuleException("Invalid expression: " + expression, source, e);
    }
}
项目:intellij-ce-playground    文件:ScriptSupport.java   
public String evaluate(MatchResult result, PsiElement context) {
  try {
    final Binding binding = new Binding();

    if (result != null) {
      for(MatchResult r:result.getAllSons()) {
        if (r.isMultipleMatch()) {
          final ArrayList<PsiElement> elements = new ArrayList<PsiElement>();
          for (MatchResult r2 : r.getAllSons()) {
            elements.add(StructuralSearchUtil.getParentIfIdentifier(r2.getMatch()));
          }
          binding.setVariable(r.getName(), elements);
        }
        else {
          binding.setVariable(r.getName(), StructuralSearchUtil.getParentIfIdentifier(r.getMatch()));
        }
      }
    }

    if (context == null) {
      context = result.getMatch();
    }
    context = StructuralSearchUtil.getParentIfIdentifier(context);
    binding.setVariable("__context__", context);
    script.setBinding(binding);

    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);
  }
}
项目:intellij-ce-playground    文件:GroovyCompilerWrapper.java   
private void addErrorMessage(GroovyRuntimeException exception) {
  ASTNode astNode = exception.getNode();
  ModuleNode module = exception.getModule();
  if (module == null) {
    module = findModule(astNode);
  }
  String moduleName = module == null ? "<no module>" : module.getDescription();

  int lineNumber = astNode == null ? -1 : astNode.getLineNumber();
  int columnNumber = astNode == null ? -1 : astNode.getColumnNumber();

  collector.add(new CompilerMessage(GroovyCompilerMessageCategories.ERROR, getExceptionMessage(exception), moduleName, lineNumber, columnNumber));
}
项目:intellij-ce-playground    文件:GroovyCompilerWrapper.java   
@NotNull
private static String getExceptionMessage(GroovyRuntimeException exception) {
  if (exception.getCause() instanceof ClassNotFoundException) {
    String className = exception.getCause().getMessage();
    return "An error occurred while trying to load a required class " + className + "." +
             " Please ensure it's present in the project dependencies. " +
             "See the message and the stack trace below for reference\n\n" + getStackTrace(exception);
  }

  String message = exception.getMessageWithoutLocationText();
  return message == null ? getStackTrace(exception) : message;
}
项目:intellij-ce-playground    文件:GroovyCompilerWrapper.java   
@NotNull
private static String getStackTrace(GroovyRuntimeException exception) {
  String message;StringWriter stringWriter = new StringWriter();
  //noinspection IOResourceOpenedButNotSafelyClosed
  PrintWriter writer = new PrintWriter(stringWriter);
  exception.printStackTrace(writer);
  message = stringWriter.getBuffer().toString();
  return message;
}
项目:ff7rl    文件:Console.java   
private Object evaluateInput(final String expression) {
    try {
        return new GroovyShell(CONSOLE_BINDING, ConsoleScriptHelper.getCompilerConfiguration()).evaluate(expression);
    } catch (final GroovyRuntimeException exception) {
        LOGGER.error(String.format("Error while evaluating [%s]", expression), exception);
        return exception.getMessage();
    }
}
项目:groovy    文件:MetaClassRegistryImpl.java   
public void onModule(final ExtensionModule module) {
    if (moduleRegistry.hasModule(module.getName())) {
    ExtensionModule loadedModule = moduleRegistry.getModule(module.getName());
    if (loadedModule.getVersion().equals(module.getVersion())) {
        // already registered
        return;
    } else {
        throw new GroovyRuntimeException("Conflicting module versions. Module ["+module.getName()+" is loaded in version "+
                loadedModule.getVersion()+" and you are trying to load version "+module.getVersion());
    }
}
    moduleRegistry.addModule(module);
    // register MetaMethods
    List<MetaMethod> metaMethods = module.getMetaMethods();
    for (MetaMethod metaMethod : metaMethods) {
        CachedClass cachedClass = metaMethod.getDeclaringClass();
        List<MetaMethod> methods = map.get(cachedClass);
        if (methods==null) {
            methods = new ArrayList<MetaMethod>(4);
            map.put(cachedClass, methods);
        }
        methods.add(metaMethod);
        if (metaMethod.isStatic()) {
            staticMethods.add(metaMethod);
        } else {
            instanceMethods.add(metaMethod);
        }
    }
}
项目:groovy    文件:SimpleTemplateEngine.java   
public Template createTemplate(Reader reader) throws CompilationFailedException, IOException {
    SimpleTemplate template = new SimpleTemplate();
    String script = template.parse(reader);
    if (verbose) {
        System.out.println("\n-- script source --");
        System.out.print(script);
        System.out.println("\n-- script end --\n");
    }
    try {
        template.script = groovyShell.parse(script, "SimpleTemplateScript" + counter++ + ".groovy");
    } catch (Exception e) {
        throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage());
    }
    return template;
}
项目:groovy    文件:ScriptBytecodeAdapter.java   
public static void setFieldOnSuper(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable {
    try {
        if (receiver instanceof Class) {
            InvokerHelper.setAttribute(receiver, messageName, messageArgument);
        } else {
            MetaClass mc = ((GroovyObject) receiver).getMetaClass();
            mc.setAttribute(senderClass, receiver, messageName, messageArgument, true, true);
        }
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
项目:groovy    文件:GroovyAssert.java   
/**
 * Asserts that the given code closure fails when it is evaluated
 * and that a particular exception 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 error message associated with the matching
 * exception is returned. If no match was found the method will fail.
 *
 * @param clazz the class of the expected exception
 * @param code  the closure that should fail
 * @return the message of the expected Throwable
 */
public static Throwable shouldFailWithCause(Class clazz, Closure code) {
    Throwable th = null;
    Throwable orig = null;
    int level = 0;
    try {
        code.call();
    } catch (GroovyRuntimeException gre) {
        orig = ScriptBytecodeAdapter.unwrap(gre);
        th = orig.getCause();
    } catch (Throwable e) {
        orig = e;
        th = orig.getCause();
    }

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

    if (orig == null) {
        fail("Closure " + code + " should have failed with an exception caused by type " + clazz.getName());
    } else if (th == null || !clazz.isInstance(th)) {
        fail("Closure " + code + " should have failed with an exception caused by type " + clazz.getName() + ", instead found these Exceptions:\n" + buildExceptionList(orig));
    }
    return th;
}
项目:groovy    文件:ScriptBytecodeAdapter.java   
public static Object unaryPlus(Object value) throws Throwable {
    try {
        return InvokerHelper.unaryPlus(value);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
项目:groovy    文件:GroovyAssert.java   
/**
 * 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;
}
项目:groovy    文件:ScriptBytecodeAdapter.java   
public static Object getField(Class senderClass, Object receiver, String messageName) throws Throwable {
    try {
        return InvokerHelper.getAttribute(receiver, messageName);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }    
}
项目:groovy    文件:XmlUtil.java   
private static void serialize(Source source, StreamResult target) {
    TransformerFactory factory = TransformerFactory.newInstance();
    setIndent(factory, 2);
    try {
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
        transformer.transform(source, target);
    }
    catch (TransformerException e) {
        throw new GroovyRuntimeException(e.getMessage());
    }
}
项目:groovy    文件:DOMCategory.java   
public static Node replaceNode(NodesHolder self, Closure c) {
    if (self.getLength() <= 0 || 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);
}
项目:groovy    文件:ScriptBytecodeAdapter.java   
public static void setProperty(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable {
    try {
        if (receiver==null) receiver= NullObject.getNullObject();
        InvokerHelper.setProperty(receiver, messageName, messageArgument);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
项目:groovy    文件:IndentPrinter.java   
public void flush() {
    try {
        out.flush();
    } catch(IOException ioe) {
        throw new GroovyRuntimeException(ioe);
    }
}
项目:groovy    文件:DefaultGroovyMethods.java   
/**
 * Iterates from this number down to the given number, inclusive,
 * decrementing by one each time.
 *
 * @param self    a Long
 * @param to the end number
 * @param closure the code to execute for each number
 * @since 1.0
 */
public static void downto(Long self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
    long to1 = to.longValue();
    if (self >= to1) {
        for (long i = self; i >= to1; i--) {
            closure.call(i);
        }
    } else
        throw new GroovyRuntimeException("The argument (" + to +
                ") to downto() cannot be greater than the value (" + self + ") it's called on.");
}
项目:AlgoTrader    文件:GrailsDataBinder.java   
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;
}
项目:groovy    文件:NodeList.java   
public Node replaceNode(Closure c) {
    if (size() <= 0 || size() > 1) {
        throw new GroovyRuntimeException(
                "replaceNode() can only be used to replace a single node, but was applied to " + size() + " nodes");
    }
    return ((Node)get(0)).replaceNode(c);
}
项目:groovy    文件:InvokerTest.java   
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);
    }
}