@JRubyMethod(required = 1, optional = 1) public RubyObject new_instance(IRubyObject[] args, Block block) { final Ruby runtime = getRuntime(); final int last = Arity.checkArgumentCount(runtime, args, 1, 2) - 1; final RubyProc proc; // Is there a supplied proc arg or do we assume a block was supplied if (args[last] instanceof RubyProc) { proc = (RubyProc) args[last]; } else { proc = runtime.newProc(Block.Type.PROC, block); } final Object[] convertedArgs = convertArguments((RubyArray) args[0]); JavaProxyInvocationHandler handler = new ProcInvocationHandler(runtime, proc); try { return JavaObject.wrap(runtime, newInstance(convertedArgs, handler)); } catch (Exception e) { RaiseException ex = runtime.newArgumentError("Constructor invocation failed: " + e.getMessage()); ex.initCause(e); throw ex; } }
private static IRubyObject callCmpMethod( ThreadContext context, IRubyObject recv, IRubyObject other, IRubyObject returnValueOnError) { Ruby runtime = context.runtime; if (recv == other) return runtime.getTrue(); try { IRubyObject result = invokedynamic(context, recv, OP_CMP, other); // This is only to prevent throwing exceptions by cmperr - it has poor performance if (result.isNil()) { return returnValueOnError; } return RubyBoolean.newBoolean(runtime, cmpint(context, result, recv, other) == 0); } catch (RaiseException e) { if (e.getException().kind_of_p(context, runtime.getStandardError()).isTrue()) { // clear error info resulting from failure to compare (JRUBY-3292) context.setErrorInfo(runtime.getNil()); return returnValueOnError; } else { throw e; } } }
public void exceptionRaised(RaiseException exception) { assert isCurrent(); RubyException rubyException = exception.getException(); Ruby runtime = rubyException.getRuntime(); if (runtime.getSystemExit().isInstance(rubyException)) { runtime .getThreadService() .getMainThread() .raise(new IRubyObject[] {rubyException}, Block.NULL_BLOCK); } else if (abortOnException(runtime)) { RubyException systemExit; if (!runtime.is1_9()) { runtime.printError(rubyException); systemExit = RubySystemExit.newInstance(runtime, 1); systemExit.message = rubyException.message; systemExit.set_backtrace(rubyException.backtrace()); } else { systemExit = rubyException; } runtime .getThreadService() .getMainThread() .raise(new IRubyObject[] {systemExit}, Block.NULL_BLOCK); return; } else if (runtime.getDebug().isTrue()) { runtime.printError(exception.getException()); } exitingException = exception; }
/** do_coerce */ protected final RubyArray doCoerce(ThreadContext context, IRubyObject other, boolean err) { if (!other.respondsTo("coerce")) { if (err) { coerceRescue(context, other); } return null; } final Ruby runtime = context.runtime; final IRubyObject $ex = context.getErrorInfo(); final IRubyObject result; try { result = coerceBody(context, other); } catch (RaiseException e) { // e.g. NoMethodError: undefined method `coerce' if (e.getException().kind_of_p(context, runtime.getStandardError()).isTrue()) { context.setErrorInfo($ex); // restore $! RubyWarnings warnings = context.runtime.getWarnings(); warnings.warn("Numerical comparison operators will no more rescue exceptions of #coerce"); warnings.warn("in the next release. Return nil in #coerce if the coercion is impossible."); if (err) { coerceFailed(context, other); } return null; } else { throw e; } } return coerceResult(runtime, result, err); }
protected boolean tryLoadingLibraryOrScript(Ruby runtime, SearchState state) { // attempt to load the found library RubyString loadNameRubyString = RubyString.newString(runtime, state.loadName); try { synchronized (loadedFeaturesInternal) { if (loadedFeaturesInternal.contains(loadNameRubyString)) { return false; } else { addLoadedFeature(loadNameRubyString); } } // otherwise load the library we've found state.library.load(runtime, false); return true; } catch (MainExitException mee) { // allow MainExitException to propagate out for exec and friends throw mee; } catch (Throwable e) { if (isJarfileLibrary(state, state.searchFile)) { return true; } removeLoadedFeature(loadNameRubyString); reraiseRaiseExceptions(e); if (runtime.getDebug().isTrue()) e.printStackTrace(runtime.getErr()); RaiseException re = newLoadErrorFromThrowable(runtime, state.searchFile, e); re.initCause(e); throw re; } }
@JRubyMethod(compat = RUBY1_9) public IRubyObject last_error(ThreadContext context) { RaiseException lastError = transcoder.getLastError(); if (lastError != null) return lastError.getException(); return context.nil; }
/** * Prints a Ruby backtrace. * * @param re The exception * @return */ RaiseException printRubyStacktrace(RaiseException re) { System.err.println(re.getException().getMetaClass() + ":" + re.getException().toString()); RubyArray rubyStackTrace = (RubyArray) re.getException().backtrace(); for (Object stackLine : rubyStackTrace) { System.err.println("\tat " + stackLine); } return re; }
@JRubyMethod(module = true) public static IRubyObject timeout( final ThreadContext context, IRubyObject timeout, IRubyObject seconds, IRubyObject exceptionType, Block block) { // No seconds, just yield if (seconds.isNil() || Helpers.invoke(context, seconds, "zero?").isTrue()) { return block.yieldSpecific(context); } final Ruby runtime = context.runtime; // No timeout in critical section if (runtime.getThreadService().getCritical()) { return raiseBecauseCritical(context); } final RubyThread currentThread = context.getThread(); final AtomicBoolean latch = new AtomicBoolean(false); IRubyObject id = new RubyObject(runtime, runtime.getObject()); RubyClass anonException = (RubyClass) runtime.getClassFromPath("Timeout::AnonymousException"); Runnable timeoutRunnable = exceptionType.isNil() ? prepareRunnable(currentThread, runtime, latch, id) : prepareRunnableWithException(currentThread, exceptionType, runtime, latch); Future timeoutFuture = null; try { try { timeoutFuture = timeoutExecutor.schedule( timeoutRunnable, (long) (seconds.convertToFloat().getDoubleValue() * 1000000), TimeUnit.MICROSECONDS); return block.yield(context, seconds); } finally { killTimeoutThread(context, timeoutFuture, latch); } } catch (RaiseException re) { // if it's the exception we're expecting if (re.getException().getMetaClass() == anonException) { // and we were not given a specific exception if (exceptionType.isNil()) { // and it's the exception intended for us if (re.getException().getInternalVariable("__identifier__") == id) { return raiseTimeoutError(context, re); } } } // otherwise, rethrow throw re; } }
public void testRubyExceptionWithoutCause() throws Exception { try { RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter(); evaler.eval(runtime, "no_method_with_this_name"); fail("Expected ScriptException"); } catch (RaiseException re) { assertEquals( "(NameError) undefined local variable or method `no_method_with_this_name' for main:Object", re.getMessage()); } }
@JRubyMethod(visibility = PRIVATE) public IRubyObject initialize( ThreadContext context, IRubyObject src, IRubyObject dest, IRubyObject _opt) { Ruby runtime = context.runtime; EncodingService encodingService = runtime.getEncodingService(); // both may be null Encoding srcEncoding = encodingService.getEncodingFromObjectNoError(src); Encoding destEncoding = encodingService.getEncodingFromObjectNoError(dest); int flags = 0; IRubyObject replace = context.nil; if (srcEncoding == destEncoding && srcEncoding != null) { throw runtime.newConverterNotFoundError( "code converter not found (" + srcEncoding + " to " + destEncoding + ")"); } // Ensure we'll be able to get charsets fo these encodings try { if (srcEncoding != destEncoding) { if (srcEncoding != null) encodingService.charsetForEncoding(srcEncoding); if (destEncoding != null) encodingService.charsetForEncoding(destEncoding); } } catch (RaiseException e) { if (e.getException().getMetaClass().getBaseName().equals("CompatibilityError")) { throw runtime.newConverterNotFoundError( "code converter not found (" + srcEncoding + " to " + destEncoding + ")"); } else { throw e; } } if (!_opt.isNil()) { if (_opt instanceof RubyHash) { RubyHash opt = (RubyHash) _opt; flags |= EncodingUtils.econvPrepareOpts(context, opt, new IRubyObject[] {opt}); IRubyObject value = opt.fastARef(runtime.newSymbol("replace")); if (value != null) { replace = value; } } else { flags = (int) _opt.convertToInteger().getLongValue(); replace = context.nil; } } transcoder = new CharsetTranscoder(context, destEncoding, srcEncoding, flags, replace); return context.runtime.getNil(); }
public void onDrawFrame(javax.microedition.khronos.opengles.GL10 gl) { if (callbackProcs[CB_DRAW_FRAME] != null) { try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_DRAW_FRAME], "call", JavaUtil.convertJavaToRuby(getRuby(), gl)); } catch (RaiseException re) { re.printStackTrace(); } } }
public void onSignalStrengthsChanged(android.telephony.SignalStrength signalStrength) { if (callbackProcs[CB_SIGNAL_STRENGTHS_CHANGED] != null) { try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_SIGNAL_STRENGTHS_CHANGED], "call", JavaUtil.convertJavaToRuby(getRuby(), signalStrength)); } catch (RaiseException re) { re.printStackTrace(); } } }
public JavaObject newInstance(final IRubyObject self, Object[] args) throws RaiseException { final Ruby runtime = getRuntime(); JavaProxyInvocationHandler handler = new MethodInvocationHandler(runtime, self); try { return JavaObject.wrap(runtime, newInstance(args, handler)); } catch (Throwable t) { while (t.getCause() != null) t = t.getCause(); RaiseException ex = runtime.newArgumentError("Constructor invocation failed: " + t.getMessage()); ex.initCause(t); throw ex; } }
public void onDataConnectionStateChanged(int state, int networkType) { if (callbackProcs[CB_DATA_CONNECTION_STATE_CHANGED] != null) { try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_DATA_CONNECTION_STATE_CHANGED], "call", JavaUtil.convertJavaToRuby(getRuby(), state), JavaUtil.convertJavaToRuby(getRuby(), networkType)); } catch (RaiseException re) { re.printStackTrace(); } } }
public void onClick(android.content.DialogInterface dialog, int which) { if (callbackProcs[CB_CLICK] != null) { try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_CLICK], "call", JavaUtil.convertJavaToRuby(getRuby(), dialog), JavaUtil.convertJavaToRuby(getRuby(), which)); } catch (RaiseException re) { re.printStackTrace(); } } }
public void onSurfaceChanged(javax.microedition.khronos.opengles.GL10 gl, int width, int height) { if (callbackProcs[CB_SURFACE_CHANGED] != null) { try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_SURFACE_CHANGED], "call", JavaUtil.convertJavaToRuby(getRuby(), gl), JavaUtil.convertJavaToRuby(getRuby(), width), JavaUtil.convertJavaToRuby(getRuby(), height)); } catch (RaiseException re) { re.printStackTrace(); } } }
private RubyClass findClass(String className) { RubyModule classInstance; try { classInstance = runtime.getClassFromPath(className); } catch (RaiseException e) { if (runtime.getModule("NameError").isInstance(e.getException())) { throw runtime.newArgumentError("undefined class/module " + className); } throw e; } if (!(classInstance instanceof RubyClass)) { throw runtime.newArgumentError(className + " does not refer class"); // sic } return (RubyClass) classInstance; }
public void onDataActivity(int direction) { if (callbackProcs[CB_DATA_ACTIVITY] != null) { super.onDataActivity(direction); try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_DATA_ACTIVITY], "call", JavaUtil.convertJavaToRuby(getRuby(), direction)); } catch (RaiseException re) { re.printStackTrace(); } } else { super.onDataActivity(direction); } }
public void onCellLocationChanged(android.telephony.CellLocation location) { if (callbackProcs[CB_CELL_LOCATION_CHANGED] != null) { super.onCellLocationChanged(location); try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_CELL_LOCATION_CHANGED], "call", JavaUtil.convertJavaToRuby(getRuby(), location)); } catch (RaiseException re) { re.printStackTrace(); } } else { super.onCellLocationChanged(location); } }
public void onCallForwardingIndicatorChanged(boolean cfi) { if (callbackProcs[CB_CALL_FORWARDING_INDICATOR_CHANGED] != null) { super.onCallForwardingIndicatorChanged(cfi); try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_CALL_FORWARDING_INDICATOR_CHANGED], "call", JavaUtil.convertJavaToRuby(getRuby(), cfi)); } catch (RaiseException re) { re.printStackTrace(); } } else { super.onCallForwardingIndicatorChanged(cfi); } }
public void onSignalStrengthChanged(int asu) { if (callbackProcs[CB_SIGNAL_STRENGTH_CHANGED] != null) { super.onSignalStrengthChanged(asu); try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_SIGNAL_STRENGTH_CHANGED], "call", JavaUtil.convertJavaToRuby(getRuby(), asu)); } catch (RaiseException re) { re.printStackTrace(); } } else { super.onSignalStrengthChanged(asu); } }
public void onMessageWaitingIndicatorChanged(boolean mwi) { if (callbackProcs[CB_MESSAGE_WAITING_INDICATOR_CHANGED] != null) { super.onMessageWaitingIndicatorChanged(mwi); try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_MESSAGE_WAITING_INDICATOR_CHANGED], "call", JavaUtil.convertJavaToRuby(getRuby(), mwi)); } catch (RaiseException re) { re.printStackTrace(); } } else { super.onMessageWaitingIndicatorChanged(mwi); } }
public void onSurfaceCreated( javax.microedition.khronos.opengles.GL10 gl, javax.microedition.khronos.egl.EGLConfig config) { if (callbackProcs[CB_SURFACE_CREATED] != null) { try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_SURFACE_CREATED], "call", JavaUtil.convertJavaToRuby(getRuby(), gl), JavaUtil.convertJavaToRuby(getRuby(), config)); } catch (RaiseException re) { re.printStackTrace(); } } }
public void onServiceStateChanged(android.telephony.ServiceState serviceState) { if (callbackProcs[CB_SERVICE_STATE_CHANGED] != null) { super.onServiceStateChanged(serviceState); try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_SERVICE_STATE_CHANGED], "call", JavaUtil.convertJavaToRuby(getRuby(), serviceState)); } catch (RaiseException re) { re.printStackTrace(); } } else { super.onServiceStateChanged(serviceState); } }
private boolean checkStreamSyntax(Ruby runtime, InputStream in, String filename) { try { runtime.parseFromMain(in, filename); config.getOutput().println("Syntax OK"); return true; } catch (RaiseException re) { if (re.getException().getMetaClass().getBaseName().equals("SyntaxError")) { config .getError() .println("SyntaxError in " + re.getException().message(runtime.getCurrentContext())); } else { throw re; } return false; } }
private <T> T call( MethodType type, Class<T> returnType, Object receiver, String methodName, Block block, EmbedEvalUnit unit, Object... args) { if (methodName == null || methodName.length() == 0) { return null; } Ruby runtime = container.getProvider().getRuntime(); RubyObject rubyReceiver = getReceiverObject(runtime, receiver); boolean sharing_variables = true; Object obj = container.getAttribute(AttributeName.SHARING_VARIABLES); if (obj != null && obj instanceof Boolean && ((Boolean) obj) == false) { sharing_variables = false; } try { if (sharing_variables) { ManyVarsDynamicScope scope; if (unit != null && unit.getScope() != null) scope = unit.getScope(); else scope = EmbedRubyRuntimeAdapterImpl.getManyVarsDynamicScope(container, 0); container.getVarMap().inject(scope, 0, rubyReceiver); runtime.getCurrentContext().pushScope(scope); } IRubyObject result = callEachType(type, rubyReceiver, methodName, block, args); if (sharing_variables) { container.getVarMap().retrieve(rubyReceiver); } if (!(result instanceof RubyNil) && returnType != null) { Object ret = JavaEmbedUtils.rubyToJava(runtime, result, returnType); return ret != null ? returnType.cast(ret) : null; } return null; } catch (RaiseException e) { runtime.printError(e.getException()); throw new InvokeFailedException(e.getMessage(), e); } catch (Throwable e) { throw new InvokeFailedException(e); } finally { if (sharing_variables) { runtime.getCurrentContext().popScope(); } } }
public void onCallStateChanged(int state, java.lang.String incomingNumber) { if (callbackProcs[CB_CALL_STATE_CHANGED] != null) { super.onCallStateChanged(state, incomingNumber); try { RuntimeHelpers.invoke( getRuby().getCurrentContext(), callbackProcs[CB_CALL_STATE_CHANGED], "call", JavaUtil.convertJavaToRuby(getRuby(), state), JavaUtil.convertJavaToRuby(getRuby(), incomingNumber)); } catch (RaiseException re) { re.printStackTrace(); } } else { super.onCallStateChanged(state, incomingNumber); } }
@JRubyMethod(rest = true) public RubyObject new_instance2(IRubyObject[] args, Block unusedBlock) { final Ruby runtime = getRuntime(); Arity.checkArgumentCount(runtime, args, 2, 2); final IRubyObject self = args[0]; final Object[] convertedArgs = convertArguments((RubyArray) args[1]); // constructor arguments JavaProxyInvocationHandler handler = new MethodInvocationHandler(runtime, self); try { return JavaObject.wrap(runtime, newInstance(convertedArgs, handler)); } catch (Exception e) { RaiseException ex = runtime.newArgumentError("Constructor invocation failed: " + e.getMessage()); ex.initCause(e); throw ex; } }
@JRubyMethod(module = true) public static IRubyObject timeout( final ThreadContext context, IRubyObject timeout, IRubyObject seconds, Block block) { // No seconds, just yield if (seconds.isNil() || Helpers.invoke(context, seconds, "zero?").isTrue()) { return block.yieldSpecific(context); } final Ruby runtime = context.runtime; // No timeout in critical section if (runtime.getThreadService().getCritical()) { return raiseBecauseCritical(context); } final RubyThread currentThread = context.getThread(); final AtomicBoolean latch = new AtomicBoolean(false); IRubyObject id = new RubyObject(runtime, runtime.getObject()); Runnable timeoutRunnable = prepareRunnable(currentThread, runtime, latch, id); Future timeoutFuture = null; try { try { timeoutFuture = timeoutExecutor.schedule( timeoutRunnable, (long) (seconds.convertToFloat().getDoubleValue() * 1000000), TimeUnit.MICROSECONDS); return block.yield(context, seconds); } finally { killTimeoutThread(context, timeoutFuture, latch); } } catch (RaiseException re) { if (re.getException().getInternalVariable("__identifier__") == id) { return raiseTimeoutError(context, re); } else { throw re; } } }
public void stop() throws Exception { try { // We call the script with receiver = null - this causes the method to be called on the top // level // script container.callMethod(null, "vertx_stop"); } catch (InvokeFailedException e) { Throwable cause = e.getCause(); if (cause instanceof RaiseException) { // Gosh, this is a bit long winded! RaiseException re = (RaiseException) cause; String msg = "(NoMethodError) undefined method `vertx_stop'"; if (re.getMessage().startsWith(msg)) { // OK - method is not mandatory return; } } throw e; } }