@JRubyMethod(required = 1, optional = 1) public IRubyObject seek(ThreadContext context, IRubyObject[] args) { Ruby runtime = context.runtime; checkFrozen(); checkFinalized(); int offset = RubyNumeric.num2int(args[0]); IRubyObject whence = context.nil; if (args.length > 1 && !args[0].isNil()) whence = args[1]; checkOpen(); switch (whence.isNil() ? 0 : RubyNumeric.num2int(whence)) { case 0: break; case 1: offset += ptr.pos; break; case 2: offset += ptr.string.size(); break; default: throw runtime.newErrnoEINVALError("invalid whence"); } if (offset < 0) throw runtime.newErrnoEINVALError("invalid seek value"); ptr.pos = offset; return RubyFixnum.zero(runtime); }
public void load(final Ruby ruby, boolean bln) { this.ruby = ruby; RubyModule nio = ruby.defineModule("NIO"); RubyClass selector = ruby.defineClassUnder( "Selector", ruby.getObject(), new ObjectAllocator() { public IRubyObject allocate(Ruby ruby, RubyClass rc) { return new Selector(ruby, rc); } }, nio); selector.defineAnnotatedMethods(Selector.class); RubyClass monitor = ruby.defineClassUnder( "Monitor", ruby.getObject(), new ObjectAllocator() { public IRubyObject allocate(Ruby ruby, RubyClass rc) { return new Monitor(ruby, rc); } }, nio); monitor.defineAnnotatedMethods(Monitor.class); }
public void testUnicodeChars() throws Exception { File file = new File("unicodeáéíóú"); if (file.exists()) { if (!file.delete()) { fail("Unable to delete file: " + file); } } try { if (!file.mkdirs()) { fail("Unable to create directory: " + file); } Ruby runtime; RubyInstanceConfig.nativeEnabled = false; runtime = Ruby.newInstance(); JRubyFile rubyFile = RubyFile.file(RubyString.newString(runtime, file.getAbsolutePath())); assertTrue(rubyFile.exists()); assertTrue(file.exists()); assertTrue(file.isDirectory()); try { assertTrue(runtime.getPosix().stat(rubyFile.getAbsolutePath()).isDirectory()); } catch (Exception e) { throw new RuntimeException("Expecting posix layer to work properly", e); } } finally { if (file.exists()) { file.delete(); } } }
@JRubyMethod(name = {"eof", "eof?"}) public IRubyObject eof(ThreadContext context) { checkReadable(); Ruby runtime = context.runtime; if (ptr.pos < ptr.string.size()) return runtime.getFalse(); return runtime.getTrue(); }
public static IRubyObject interpretCommonEval( Ruby runtime, String file, int lineNumber, String backtraceName, RootNode rootNode, IRubyObject self, Block block) { // SSS FIXME: Is this required here since the IR version cannot change from eval-to-eval? This // is much more of a global setting. boolean is_1_9 = runtime.is1_9(); if (is_1_9) IRBuilder.setRubyVersion("1.9"); StaticScope ss = rootNode.getStaticScope(); IRScope containingIRScope = getEvalContainerScope(runtime, ss); IREvalScript evalScript = IRBuilder.createIRBuilder(runtime, runtime.getIRManager()) .buildEvalRoot(ss, containingIRScope, file, lineNumber, rootNode); evalScript.prepareForInterpretation(false); // evalScript.runCompilerPass(new CallSplitter()); ThreadContext context = runtime.getCurrentContext(); runBeginEndBlocks( evalScript.getBeginBlocks(), context, self, null); // FIXME: No temp vars yet right? IRubyObject rv = evalScript.call( context, self, evalScript.getStaticScope().getModule(), rootNode.getScope(), block, backtraceName); runBeginEndBlocks(evalScript.getEndBlocks(), context, self, null); // FIXME: No temp vars right? return rv; }
@JRubyMethod( name = "raise", optional = 3, frame = true, module = true, visibility = Visibility.PRIVATE, omit = true) public static IRubyObject rbRaise( ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { Ruby runtime = context.runtime; // Check for a Java exception ConcreteJavaProxy exception = null; if (args.length == 0 && runtime.getGlobalVariables().get("$!") instanceof ConcreteJavaProxy) { exception = (ConcreteJavaProxy) runtime.getGlobalVariables().get("$!"); } else if (args.length == 1 && args[0] instanceof ConcreteJavaProxy) { exception = (ConcreteJavaProxy) args[0]; } if (exception != null) { // looks like someone's trying to raise a Java exception. Let them. Object maybeThrowable = exception.getObject(); if (maybeThrowable instanceof Throwable) { // yes, we're cheating here. Helpers.throwException((Throwable) maybeThrowable); return recv; // not reached } else { throw runtime.newTypeError("can't raise a non-Throwable Java object"); } } else { return RubyKernel.raise(context, recv, args, block); } }
/** * Evaluate the given string. * * @param context the current thread's context * @param self the self to evaluate under * @param src The string containing the text to be evaluated * @param file The filename to use when reporting errors during the evaluation * @param lineNumber that the eval supposedly starts from * @return An IRubyObject result from the evaluation */ public static IRubyObject evalSimple( ThreadContext context, IRubyObject self, RubyString src, String file, int lineNumber) { // this is ensured by the callers assert file != null; Ruby runtime = src.getRuntime(); // no binding, just eval in "current" frame (caller's frame) RubyString source = src.convertToString(); DynamicScope evalScope = context.getCurrentScope().getEvalScope(runtime); evalScope.getStaticScope().determineModule(); try { Node node = runtime.parseEval(source.getByteList(), file, evalScope, lineNumber); if (runtime.getInstanceConfig().getCompileMode() == CompileMode.OFFIR) { // SSS FIXME: AST interpreter passed both a runtime (which comes from the source string) // and the thread-context rather than fetch one from the other. Why is that? return Interpreter.interpretSimpleEval(runtime, file, lineNumber, "(eval)", node, self); } else { return INTERPRET_EVAL( runtime, context, file, lineNumber, node, "(eval)", self, Block.NULL_BLOCK); } } catch (JumpException.BreakJump bj) { throw runtime.newLocalJumpError( RubyLocalJumpError.Reason.BREAK, (IRubyObject) bj.getValue(), "unexpected break"); } catch (StackOverflowError soe) { throw runtime.newSystemStackError("stack level too deep", soe); } }
private IRubyObject uclassUnmarshall() throws IOException { RubySymbol className = (RubySymbol) unmarshalObject(false); RubyClass type = (RubyClass) runtime.getClassFromPath(className.asJavaString()); // singleton, raise error if (type.isSingleton()) throw runtime.newTypeError("singleton can't be loaded"); // All "C" marshalled objects descend from core classes, which are all at least RubyObject RubyObject result = (RubyObject) unmarshalObject(); // if result is a module or type doesn't extend result's class... if (result.getMetaClass() == runtime.getModule() || !type.isKindOfModule(result.getMetaClass())) { // if allocators do not match, error // Note: MRI is a bit different here, and tests TYPE(type.allocate()) != TYPE(result) if (type.getAllocator() != result.getMetaClass().getRealClass().getAllocator()) { throw runtime.newArgumentError("dump format error (user class)"); } } result.setMetaClass(type); return result; }
public IRubyObject execute(IRubyObject recv, IRubyObject[] oargs, Block block) { if (arityValue >= 0) { if (oargs.length != arityValue) { throw recv.getRuntime() .newArgumentError( "wrong number of arguments (" + oargs.length + " for " + arityValue + ")"); } } else { if (oargs.length < -(1 + arityValue)) { throw recv.getRuntime() .newArgumentError( "wrong number of arguments (" + oargs.length + " for " + -(1 + arityValue) + ")"); } } try { return call(recv, oargs, block); } catch (RaiseException e) { throw e; } catch (JumpException e) { throw e; } catch (ThreadKill e) { throw e; } catch (MainExitException e) { throw e; } catch (Exception e) { Ruby runtime = recv.getRuntime(); runtime.getJavaSupport().handleNativeException(e, getTarget()); return runtime.getNil(); } }
private Object cache( ThreadContext context, DynamicScope currDynScope, IRubyObject self, Object[] temp, Ruby runtime, Object constant) { StaticScope staticScope = (StaticScope) definingScope.retrieve(context, self, currDynScope, temp); RubyModule object = runtime.getObject(); // SSS FIXME: IRManager objects dont have a static-scope yet, so this hack of looking up the // module right away // This IR needs fixing! constant = (staticScope == null) ? object.getConstant(constName) : staticScope.getConstantInner(runtime, constName, object); if (constant == null) { constant = UndefinedValue.UNDEFINED; } else { // recache generation = runtime.getConstantInvalidator().getData(); cachedConstant = constant; } return constant; }
@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; } }
@JRubyMethod(name = "completion_case_fold", module = true, visibility = Visibility.PRIVATE) public static IRubyObject s_get_completion_case_fold(ThreadContext context, IRubyObject recv) throws Exception { Ruby runtime = context.getRuntime(); runtime.secure(4); return COMPLETION_CASE_FOLD; }
@JRubyMethod( name = { "basic_quote_characters", "basic_quote_characters=", "completer_quote_characters", "completer_quote_characters=", "completer_word_break_characters", "completer_word_break_characters=", "completion_append_character", "completion_proc", "emacs_editing_mode", "emacs_editing_mode?", "filename_quote_characters", "filename_quote_characters=", "vi_editing_mode", "vi_editing_mode?", "set_screen_size" }, frame = true, module = true, visibility = Visibility.PRIVATE, compat = CompatVersion.RUBY1_9) public static IRubyObject unimplemented19(ThreadContext context, IRubyObject recv) throws Exception { Ruby runtime = context.getRuntime(); runtime.secure(4); String err = context.getFrameName() + "() function is unimplemented on this machine"; throw runtime.newNotImplementedError(err); }
public static void createX509CRL(Ruby runtime, RubyModule mX509) { RubyClass cX509CRL = mX509.defineClassUnder("CRL", runtime.getObject(), X509CRL_ALLOCATOR); RubyClass openSSLError = runtime.getModule("OpenSSL").getClass("OpenSSLError"); mX509.defineClassUnder("CRLError", openSSLError, openSSLError.getAllocator()); cX509CRL.defineAnnotatedMethods(X509CRL.class); }
private IRubyObject callEachType( MethodType type, IRubyObject rubyReceiver, String methodName, Block block, Object... args) { Ruby runtime = rubyReceiver.getRuntime(); IRubyObject[] rubyArgs = null; if (args != null && args.length > 0) { rubyArgs = JavaUtil.convertJavaArrayToRuby(runtime, args); for (int i = 0; i < rubyArgs.length; i++) { IRubyObject obj = rubyArgs[i]; if (obj instanceof JavaObject) { rubyArgs[i] = Java.wrap(runtime, obj); } } } ThreadContext context = runtime.getCurrentContext(); switch (type) { case CALLMETHOD_NOARG: return RuntimeHelpers.invoke(context, rubyReceiver, methodName); case CALLMETHOD: return RuntimeHelpers.invoke(context, rubyReceiver, methodName, rubyArgs); case CALLMETHOD_WITHBLOCK: return RuntimeHelpers.invoke(context, rubyReceiver, methodName, rubyArgs, block); case CALLSUPER: return RuntimeHelpers.invokeSuper(context, rubyReceiver, rubyArgs, Block.NULL_BLOCK); case CALLSUPER_WITHBLOCK: return RuntimeHelpers.invokeSuper(context, rubyReceiver, rubyArgs, block); default: break; } return null; }
public ByteList doReceiveNonblock(ThreadContext context, int length) { Ruby runtime = context.runtime; Channel channel = getChannel(); if (!(channel instanceof SelectableChannel)) { if (runtime.is1_9()) { throw runtime.newErrnoEAGAINReadableError( channel.getClass().getName() + " does not support nonblocking"); } else { throw runtime.newErrnoEAGAINError( channel.getClass().getName() + " does not support nonblocking"); } } SelectableChannel selectable = (SelectableChannel) channel; synchronized (selectable.blockingLock()) { boolean oldBlocking = selectable.isBlocking(); try { selectable.configureBlocking(false); try { return doReceive(context, length); } finally { selectable.configureBlocking(oldBlocking); } } catch (IOException e) { throw runtime.newIOErrorFromException(e); } } }
@JRubyMethod(rest = true) public static IRubyObject set_types(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); RubyArray types = RubyArray.newArray(runtime, args); RubyArray type_strings = RubyArray.newArray(runtime); for (IRubyObject arg : args) { if (arg instanceof RubyClass) { type_strings.append(arg); } else if (arg instanceof RubyArray) { for (IRubyObject sub_arg : arg.convertToArray().toJavaArray()) { if (sub_arg instanceof RubyClass) { type_strings.append(sub_arg); } else { throw runtime.newArgumentError("Invalid type given"); } } } else { throw runtime.newArgumentError("Invalid type given"); } } api.setInstanceVariable(recv, "@field_types", type_strings); return types; }
@Override @JRubyMethod public IRubyObject close_write(ThreadContext context) { Ruby runtime = context.runtime; if (!openFile.isWritable()) { return runtime.getNil(); } if (openFile.getPipeStream() == null && openFile.isReadable()) { throw runtime.newIOError("closing non-duplex IO for writing"); } if (!openFile.isReadable()) { close(); } else { // shutdown write try { shutdownInternal(context, 1); } catch (BadDescriptorException e) { throw runtime.newErrnoEBADFError(); } } return context.nil; }
private ByteList doReceive(ThreadContext context, int length) { Ruby runtime = context.runtime; ByteBuffer buf = ByteBuffer.allocate(length); try { context.getThread().beforeBlockingCall(); int read = openFile.getMainStreamSafe().getDescriptor().read(buf); if (read == 0) return null; return new ByteList(buf.array(), 0, buf.position()); } catch (BadDescriptorException e) { throw runtime.newIOError("bad descriptor"); } catch (IOException e) { // All errors to sysread should be SystemCallErrors, but on a closed stream // Ruby returns an IOError. Java throws same exception for all errors so // we resort to this hack... if ("Socket not open".equals(e.getMessage())) { throw runtime.newIOError(e.getMessage()); } throw runtime.newSystemCallError(e.getMessage()); } finally { context.getThread().afterBlockingCall(); } }
public static String getNormalizedHome(Ruby runtime) { normalizedHome = runtime.getJRubyHome(); if ((normalizedHome == null) && Ruby.isSecurityRestricted()) { normalizedHome = "SECURITY RESTRICTED"; } return normalizedHome; }
public int call(Object a1, Object a2) throws Exception { StoreContext ctx = (StoreContext) a2; int ok = ((Integer) a1).intValue(); IRubyObject proc = (IRubyObject) ctx.getExtraData(1); if (null == proc) { proc = (IRubyObject) ctx.ctx.getExtraData(0); } if (null == proc) { return ok; } if (!proc.isNil()) { Ruby rt = proc.getRuntime(); RubyClass cStoreContext = Utils.getClassFromPath(rt, "OpenSSL::X509::StoreContext"); X509StoreCtx rctx = new X509StoreCtx(rt, cStoreContext, ctx); RubyBoolean rok = rt.newBoolean(ok != 0); IRubyObject ret = proc.callMethod(rt.getCurrentContext(), "call", new IRubyObject[] {rok, rctx}); if (ret.isTrue()) { ctx.setError(X509Utils.V_OK); ok = 1; } else { if (ctx.getError() == X509Utils.V_OK) { ctx.setError(X509Utils.V_ERR_CERT_REJECTED); } ok = 0; } } return ok; }
public static IRubyObject lexicalSearchConst( ThreadContext context, StaticScope scope, MutableCallSite site, String constName, boolean noPrivateConsts) throws Throwable { Ruby runtime = context.runtime; IRubyObject constant = scope.getConstantInner(constName); if (constant == null) { constant = UndefinedValue.UNDEFINED; } SwitchPoint switchPoint = (SwitchPoint) runtime.getConstantInvalidator(constName).getData(); // bind constant until invalidated MethodHandle target = Binder.from(site.type()).drop(0, 2).constant(constant); MethodHandle fallback = Binder.from(site.type()) .append(site, constName) .append(noPrivateConsts) .invokeStatic(LOOKUP, Bootstrap.class, "lexicalSearchConst"); site.setTarget(switchPoint.guardWithTest(target, fallback)); return constant; }
public static RubyClass createPointerClass(Ruby runtime, RubyModule module) { RubyClass pointerClass = module.defineClassUnder( "Pointer", module.getClass(AbstractMemory.ABSTRACT_MEMORY_RUBY_CLASS), RubyInstanceConfig.REIFY_RUBY_CLASSES ? new ReifyingAllocator(Pointer.class) : PointerAllocator.INSTANCE); pointerClass.defineAnnotatedMethods(Pointer.class); pointerClass.defineAnnotatedConstants(Pointer.class); pointerClass.setReifiedClass(Pointer.class); pointerClass.kindOf = new RubyModule.KindOf() { @Override public boolean isKindOf(IRubyObject obj, RubyModule type) { return obj instanceof Pointer && super.isKindOf(obj, type); } }; module.defineClassUnder( "NullPointerError", runtime.getRuntimeError(), runtime.getRuntimeError().getAllocator()); // Add Pointer::NULL as a constant Pointer nullPointer = new Pointer(runtime, pointerClass, new NullMemoryIO(runtime)); pointerClass.setConstant("NULL", nullPointer); runtime .getNilClass() .addMethod("to_ptr", new NilToPointerMethod(runtime.getNilClass(), nullPointer)); return pointerClass; }
/** * Create a new JRuby-scripted object from the given script source. * * @param scriptSource the script source text * @param interfaces the interfaces that the scripted Java object is to implement * @param classLoader the {@link ClassLoader} to create the script proxy with * @return the scripted Java object * @throws JumpException in case of JRuby parsing failure */ public static Object createJRubyObject( String scriptSource, Class[] interfaces, ClassLoader classLoader) { Ruby ruby = initializeRuntime(); Node scriptRootNode = (oldParseMethod != null ? (Node) ReflectionUtils.invokeMethod( oldParseMethod, ruby, new Object[] {scriptSource, "", null}) : ruby.parse(scriptSource, "", null, 0)); IRubyObject rubyObject = ruby.eval(scriptRootNode); if (rubyObject instanceof RubyNil) { String className = findClassName(scriptRootNode); rubyObject = ruby.evalScript("\n" + className + ".new"); } // still null? if (rubyObject instanceof RubyNil) { throw new IllegalStateException( "Compilation of JRuby script returned RubyNil: " + rubyObject); } return Proxy.newProxyInstance( classLoader, interfaces, new RubyObjectInvocationHandler(rubyObject, ruby)); }
protected LoadServiceResource tryResourceFromCWD( SearchState state, String baseName, SuffixType suffixType) throws RaiseException { LoadServiceResource foundResource = null; for (String suffix : suffixType.getSuffixes()) { String namePlusSuffix = baseName + suffix; // check current directory; if file exists, retrieve URL and return resource try { JRubyFile file = JRubyFile.create( runtime.getCurrentDirectory(), RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix)); debugLogTry("resourceFromCWD", file.toString()); if (file.isFile() && file.isAbsolute() && file.canRead()) { boolean absolute = true; String s = namePlusSuffix; if (!namePlusSuffix.startsWith("./")) { s = "./" + s; } foundResource = new LoadServiceResource(file, s, absolute); debugLogFound(foundResource); state.loadName = resolveLoadName(foundResource, namePlusSuffix); break; } } catch (IllegalArgumentException illArgEx) { } catch (SecurityException secEx) { } } return foundResource; }
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; } }
/** * this method uses the appropriate lookup strategy to find a file. It is used by Kernel#require. * * @mri rb_find_file * @param name the file to find, this is a path name * @return the correct file */ protected LoadServiceResource findFileInClasspath(String name) { // Look in classpath next (we do not use File as a test since UNC names will match) // Note: Jar resources must NEVER begin with an '/'. (previous code said "always begin with a // /") ClassLoader classLoader = runtime.getJRubyClassLoader(); // handle security-sensitive case if (Ruby.isSecurityRestricted() && classLoader == null) { classLoader = runtime.getInstanceConfig().getLoader(); } // absolute classpath URI, no need to iterate over loadpaths if (name.startsWith("classpath:/")) { LoadServiceResource foundResource = getClassPathResource(classLoader, name); if (foundResource != null) { return foundResource; } } else if (name.startsWith("classpath:")) { // "relative" classpath URI name = name.substring("classpath:".length()); } for (int i = 0; i < loadPath.size(); i++) { // TODO this is really inefficient, and potentially a problem everytime anyone require's // something. // we should try to make LoadPath a special array object. RubyString entryString = loadPath.eltInternal(i).convertToString(); String entry = entryString.asJavaString(); // if entry is an empty string, skip it if (entry.length() == 0) continue; // if entry starts with a slash, skip it since classloader resources never start with a / if (entry.charAt(0) == '/' || (entry.length() > 1 && entry.charAt(1) == ':')) continue; if (entry.startsWith("classpath:/")) { entry = entry.substring("classpath:/".length()); } else if (entry.startsWith("classpath:")) { entry = entry.substring("classpath:".length()); } // otherwise, try to load from classpath (Note: Jar resources always uses '/') LoadServiceResource foundResource = getClassPathResource(classLoader, entry + "/" + name); if (foundResource != null) { return foundResource; } } // if name starts with a / we're done (classloader resources won't load with an initial /) if (name.charAt(0) == '/' || (name.length() > 1 && name.charAt(1) == ':')) return null; // Try to load from classpath without prefix. "A/b.rb" will not load as // "./A/b.rb" in a jar file. LoadServiceResource foundResource = getClassPathResource(classLoader, name); if (foundResource != null) { return foundResource; } return null; }
protected LoadServiceResource tryResourceAsIs(String namePlusSuffix) throws RaiseException { LoadServiceResource foundResource = null; try { if (!Ruby.isSecurityRestricted()) { String reportedPath = namePlusSuffix; File actualPath; // we check length == 0 for 'load', which does not use load path if (new File(reportedPath).isAbsolute()) { // it's an absolute path, use it as-is actualPath = new File(RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix)); } else { // prepend ./ if . is not already there, since we're loading based on CWD if (reportedPath.charAt(0) == '.' && reportedPath.charAt(1) == '/') { reportedPath = reportedPath.replaceFirst("\\./", runtime.getCurrentDirectory()); } actualPath = JRubyFile.create( runtime.getCurrentDirectory(), RubyFile.expandUserPath(runtime.getCurrentContext(), namePlusSuffix)); } debugLogTry("resourceAsIs", actualPath.toString()); if (actualPath.isFile() && actualPath.canRead()) { foundResource = new LoadServiceResource(actualPath, reportedPath); debugLogFound(foundResource); } } } catch (SecurityException secEx) { } return foundResource; }
@JRubyMethod public IRubyObject setsockopt( ThreadContext context, IRubyObject _level, IRubyObject _opt, IRubyObject val) { Ruby runtime = context.runtime; SocketLevel level = levelFromArg(_level); SocketOption opt = optionFromArg(_opt); try { Channel channel = getOpenChannel(); SocketType socketType = SocketType.forChannel(channel); switch (level) { case SOL_IP: case SOL_SOCKET: case SOL_TCP: case SOL_UDP: if (opt == SocketOption.SO_LINGER) { if (val instanceof RubyBoolean && !val.isTrue()) { socketType.setSoLinger(channel, false, 0); } else { int num = asNumber(val); if (num == -1) { socketType.setSoLinger(channel, false, 0); } else { socketType.setSoLinger(channel, true, num); } } } else { socketType.setSocketOption(channel, opt, asNumber(val)); } break; default: int intLevel = (int) _level.convertToInteger().getLongValue(); int intOpt = (int) _opt.convertToInteger().getLongValue(); if (IPPROTO_TCP.intValue() == intLevel && TCP_NODELAY.intValue() == intOpt) { socketType.setTcpNoDelay(channel, asBoolean(val)); } else if (IPPROTO_IP.intValue() == intLevel) { if (MulticastStateManager.IP_ADD_MEMBERSHIP == intOpt) { joinMulticastGroup(val); } } else { throw runtime.newErrnoENOPROTOOPTError(); } } } catch (BadDescriptorException e) { throw runtime.newErrnoEBADFError(); } catch (IOException e) { throw runtime.newErrnoENOPROTOOPTError(); } return runtime.newFixnum(0); }
/** * Take the boolean value and convert it to its bytes. * * @param bool The Ruby boolean value. * @return The byte array. * @since 2.0.0 */ private static RubyString toBsonBoolean(final IRubyObject bool) { final Ruby runtime = bool.getRuntime(); if (bool == runtime.getTrue()) { return RubyString.newString(runtime, TRUE_BYTES); } else { return RubyString.newString(runtime, FALSE_BYTES); } }