@JRubyMethod( name = "get_screen_size", module = true, visibility = Visibility.PRIVATE, compat = CompatVersion.RUBY1_9) public static IRubyObject s_get_screen_size(ThreadContext context, IRubyObject recv) throws Exception { Ruby runtime = context.getRuntime(); runtime.secure(4); ConsoleHolder holder = getHolder(runtime); IRubyObject[] ary = new IRubyObject[2]; ary[0] = runtime.newFixnum(holder.readline.getTermheight()); ary[1] = runtime.newFixnum(holder.readline.getTermwidth()); return RubyArray.newArray(runtime, ary); }
public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime,Date date){ if (date.getTime() == 0) { return runtime.getNil(); } gregCalendar.setTime(date); int month = gregCalendar.get(Calendar.MONTH); month++; // In Calendar January == 0, etc... RubyClass klazz = runtime.fastGetClass("Date"); return klazz.callMethod( runtime.getCurrentContext() ,"civil", new IRubyObject []{ runtime.newFixnum(gregCalendar.get(Calendar.YEAR)), runtime.newFixnum(month), runtime.newFixnum(gregCalendar.get(Calendar.DAY_OF_MONTH))}); }
@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); }
public static IRubyObject prepareRubyDateTimeFromSqlTimestamp(Ruby runtime,Timestamp stamp){ if (stamp.getTime() == 0) { return runtime.getNil(); } gregCalendar.setTime(stamp); int month = gregCalendar.get(Calendar.MONTH); month++; // In Calendar January == 0, etc... int zoneOffset = gregCalendar.get(Calendar.ZONE_OFFSET)/3600000; RubyClass klazz = runtime.fastGetClass("DateTime"); IRubyObject rbOffset = runtime.fastGetClass("Rational") .callMethod(runtime.getCurrentContext(), "new",new IRubyObject[]{ runtime.newFixnum(zoneOffset),runtime.newFixnum(24) }); return klazz.callMethod(runtime.getCurrentContext() , "civil", new IRubyObject []{runtime.newFixnum(gregCalendar.get(Calendar.YEAR)), runtime.newFixnum(month), runtime.newFixnum(gregCalendar.get(Calendar.DAY_OF_MONTH)), runtime.newFixnum(gregCalendar.get(Calendar.HOUR_OF_DAY)), runtime.newFixnum(gregCalendar.get(Calendar.MINUTE)), runtime.newFixnum(gregCalendar.get(Calendar.SECOND)), rbOffset}); }
public static void initPsychParser(Ruby runtime, RubyModule psych) { RubyClass psychParser = runtime.defineClassUnder( "Parser", runtime.getObject(), new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new PsychParser(runtime, klazz); } }, psych); psychParser.defineConstant("ANY", runtime.newFixnum(YAML_ANY_ENCODING)); psychParser.defineConstant("UTF8", runtime.newFixnum(YAML_UTF8_ENCODING)); psychParser.defineConstant("UTF16LE", runtime.newFixnum(YAML_UTF16LE_ENCODING)); psychParser.defineConstant("UTF16BE", runtime.newFixnum(YAML_UTF16BE_ENCODING)); psychParser.defineAnnotatedMethods(PsychParser.class); psych.defineClassUnder("SyntaxError", runtime.getSyntaxError(), OBJECT_ALLOCATOR); }
@Override public IRubyObject each_byte(ThreadContext context, Block block) { checkReadable(); Ruby runtime = context.runtime; ByteList bytes = data.internal.getByteList(); // Check the length every iteration, since // the block can modify this string. while (data.pos < bytes.length()) { block.yield(context, runtime.newFixnum(bytes.get((int) data.pos++) & 0xFF)); } return this; }
public static IRubyObject gethostbyaddr(ThreadContext context, IRubyObject[] args) { Ruby runtime = context.runtime; IRubyObject[] ret = new IRubyObject[4]; ret[0] = runtime.newString( Sockaddr.addressFromString(runtime, args[0].convertToString().toString()) .getCanonicalHostName()); ret[1] = runtime.newArray(); ret[2] = runtime.newFixnum(2); // AF_INET ret[3] = args[0]; return runtime.newArrayNoCopy(ret); }
@JRubyMethod(required = 1, optional = 1, visibility = PRIVATE) @Override public IRubyObject initialize(IRubyObject[] args, Block block) { Ruby runtime = getRuntime(); IRubyObject basename = args[0]; IRubyObject dir = defaultTmpDir(runtime, args); File tmp = null; synchronized (tmpFileLock) { while (true) { try { if (counter == -1) { counter = RND.nextInt() & 0xffff; } counter++; // We do this b/c make_tmpname might be overridden IRubyObject tmpname = callMethod( runtime.getCurrentContext(), "make_tmpname", new IRubyObject[] {basename, runtime.newFixnum(counter)}); tmp = JRubyFile.create( getRuntime().getCurrentDirectory(), new File(dir.convertToString().toString(), tmpname.convertToString().toString()) .getPath()); if (tmp.createNewFile()) { tmpFile = tmp; path = tmp.getPath(); try { tmpFile.deleteOnExit(); } catch (NullPointerException npe) { // See JRUBY-4624. // Due to JDK bug, NPE could be thrown // when shutdown is in progress. // Do nothing. } catch (IllegalStateException ise) { // do nothing, shutdown in progress } initializeOpen(); referenceSet.put(reaper = new Reaper(this, runtime, tmpFile, openFile), Boolean.TRUE); return this; } } catch (IOException e) { throw runtime.newIOErrorFromException(e); } } } }
@JRubyMethod(name = {"each_byte", "bytes"}) public IRubyObject each_byte(ThreadContext context, Block block) { if (!block.isGiven()) return enumeratorize(context.runtime, this, "each_byte"); checkReadable(); Ruby runtime = context.runtime; ByteList bytes = ptr.string.getByteList(); // Check the length every iteration, since // the block can modify this string. while (ptr.pos < bytes.length()) { block.yield(context, runtime.newFixnum(bytes.get((int) ptr.pos++) & 0xFF)); } return this; }
@JRubyMethod( name = "point", module = true, visibility = Visibility.PRIVATE, compat = CompatVersion.RUBY1_9) public static IRubyObject s_get_point(ThreadContext context, IRubyObject recv) throws Exception { Ruby runtime = context.getRuntime(); runtime.secure(4); ConsoleHolder holder = getHolder(runtime); if (holder.readline == null) { initReadline(runtime, holder); } CursorBuffer cb = holder.readline.getCursorBuffer(); return runtime.newFixnum(cb.cursor); }
/** * Gets a ruby array of the offsets of all members of this struct. * * @return a <tt>RubyArray</tt> containing the offsets of all members. */ @JRubyMethod(name = "offsets") public IRubyObject offsets(ThreadContext context) { Ruby runtime = context.getRuntime(); RubyArray offsets = RubyArray.newArray(runtime); for (IRubyObject name : fieldNames) { RubyArray offset = RubyArray.newArray(runtime); // Assemble a [ :name, offset ] array offset.append(name); offset.append(runtime.newFixnum(getMember(runtime, name).offset)); offsets.append(offset); } return offsets; }
public static IRubyObject gethostbyname(ThreadContext context, IRubyObject hostname) { Ruby runtime = context.runtime; try { InetAddress addr = getRubyInetAddress(hostname.convertToString().getByteList()); IRubyObject[] ret = new IRubyObject[4]; ret[0] = runtime.newString(addr.getCanonicalHostName()); ret[1] = runtime.newArray(); ret[2] = runtime.newFixnum(2); // AF_INET ret[3] = runtime.newString(new ByteList(addr.getAddress())); return runtime.newArrayNoCopy(ret); } catch (UnknownHostException e) { throw sockerr(runtime, "gethostbyname: name or service not known"); } }
/** * Output a log message * * @param logMessage * @param executionTime */ private void debug(String logMessage, Long executionTime) { Ruby runtime = getRuntime(); Connection connection_instance = (Connection) api.getInstanceVariable(this, "@connection"); RubyModule doModule = runtime.getModule(DATA_OBJECTS_MODULE_NAME); RubyClass loggerClass = doModule.getClass("Logger"); RubyClass messageClass = loggerClass.getClass("Message"); IRubyObject loggerMsg = messageClass.newInstance( runtime.getCurrentContext(), runtime.newString(logMessage), // query runtime.newString(""), // start runtime.newFixnum(executionTime), // duration Block.NULL_BLOCK); api.callMethod(connection_instance, "log", loggerMsg); }
/** * Unmarshal a java.sql.Resultset containing generated keys, and return a Ruby Fixnum with the * last key. * * @param runtime * @param rs * @return * @throws java.sql.SQLException */ public static IRubyObject unmarshal_id_result(Ruby runtime, ResultSet rs) throws SQLException { try { if (rs.next()) { if (rs.getMetaData().getColumnCount() > 0) { // TODO: Need to do check for other types here, as keys could be // of type Integer, Long or String return runtime.newFixnum(rs.getLong(1)); } } return runtime.getNil(); } finally { try { rs.close(); } catch (Exception e) { } } }
protected IRubyObject addrFor(ThreadContext context, InetSocketAddress addr, boolean reverse) { Ruby r = context.runtime; IRubyObject[] ret = new IRubyObject[4]; if (addr.getAddress() instanceof Inet6Address) { ret[0] = r.newString("AF_INET6"); } else { ret[0] = r.newString("AF_INET"); } ret[1] = r.newFixnum(addr.getPort()); String hostAddress = addr.getAddress().getHostAddress(); if (!reverse || doNotReverseLookup(context)) { ret[2] = r.newString(hostAddress); } else { ret[2] = r.newString(addr.getHostName()); } ret[3] = r.newString(hostAddress); return r.newArrayNoCopy(ret); }
@Override public void load(Ruby ruby, boolean wrap) throws IOException { RubyModule pg = ruby.defineModule("PG"); ruby.defineClassUnder( "Error", ruby.getStandardError(), ruby.getStandardError().getAllocator(), pg); RubyModule pgConstants = ruby.defineModuleUnder("Constants", pg); // create the connection status constants for (ConnectionState status : ConnectionState.values()) pgConstants.defineConstant(status.name(), ruby.newFixnum(status.ordinal())); for (TransactionStatus status : TransactionStatus.values()) pgConstants.defineConstant(status.name(), ruby.newFixnum(status.ordinal())); for (ResultStatus status : ResultStatus.values()) pgConstants.defineConstant(status.name(), ruby.newFixnum(status.ordinal())); // create the large object constants pgConstants.defineConstant("INV_READ", new RubyFixnum(ruby, LargeObjectAPI.READ)); pgConstants.defineConstant("INV_WRITE", new RubyFixnum(ruby, LargeObjectAPI.WRITE)); pgConstants.defineConstant("SEEK_SET", new RubyFixnum(ruby, LargeObjectAPI.SEEK_SET)); pgConstants.defineConstant("SEEK_END", new RubyFixnum(ruby, LargeObjectAPI.SEEK_END)); pgConstants.defineConstant("SEEK_CUR", new RubyFixnum(ruby, LargeObjectAPI.SEEK_CUR)); // create error fields objects for (ErrorField field : ErrorResponse.ErrorField.values()) pgConstants.defineConstant(field.name(), ruby.newFixnum(field.getCode())); pg.getSingletonClass().defineAnnotatedMethods(Postgresql.class); try { for (java.lang.reflect.Field field : Oid.class.getDeclaredFields()) { String name = field.getName(); int value = field.getInt(null); pgConstants.defineConstant("OID_" + name, ruby.newFixnum(value)); } } catch (Exception e) { ruby.newRuntimeError(e.getLocalizedMessage()); } pgConstants.defineConstant("INVALID_OID", ruby.newFixnum(Oid.UNSPECIFIED)); pg.includeModule(pgConstants); Connection.define(ruby, pg, pgConstants); Result.define(ruby, pg, pgConstants); }
public static IRubyObject getservbyname(ThreadContext context, IRubyObject[] args) { Ruby runtime = context.runtime; String name = args[0].convertToString().toString(); String proto = args.length == 1 ? "tcp" : args[1].convertToString().toString(); Service service = Service.getServiceByName(name, proto); int port; if (service != null) { port = service.getPort(); } else { // MRI behavior: try to convert the name string to port directly try { port = Integer.parseInt(name.trim()); } catch (NumberFormatException nfe) { throw sockerr(runtime, "no such service " + name + "/" + proto); } } return runtime.newFixnum(port); }
@JRubyMethod(name = "each_codepoint") public IRubyObject each_codepoint(ThreadContext context, Block block) { Ruby runtime = context.runtime; if (!block.isGiven()) return enumeratorize(runtime, this, "each_codepoint"); checkReadable(); Encoding enc = ptr.string.getEncoding(); byte[] unsafeBytes = ptr.string.getByteList().getUnsafeBytes(); int begin = ptr.string.getByteList().getBegin(); for (; ; ) { if (ptr.pos >= ptr.string.size()) { return this; } int c = StringSupport.codePoint(runtime, enc, unsafeBytes, begin + ptr.pos, unsafeBytes.length); int n = StringSupport.codeLength(runtime, enc, c); block.yield(context, runtime.newFixnum(c)); ptr.pos += n; } }
public static final IRubyObject newSigned16(Ruby runtime, int value) { value &= 0xffff; return runtime.newFixnum(value < 0x8000 ? value : -0x8000 + (value - 0x8000)); }
public final IRubyObject invoke(Ruby runtime, Function function, HeapInvocationBuffer args) { return returnType.callMethod( runtime.getCurrentContext(), "find", runtime.newFixnum(invoker.invokeInt(function, args))); }
@JRubyMethod(optional = 1, rest = true) public static IRubyObject execute_non_query(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); IRubyObject connection_instance = api.getInstanceVariable(recv, "@connection"); IRubyObject wrapped_jdbc_connection = api.getInstanceVariable(connection_instance, "@connection"); if (wrapped_jdbc_connection.isNil()) { throw DataObjectsUtils.newDriverError( runtime, errorName, "This connection has already been closed."); } java.sql.Connection conn = getConnection(wrapped_jdbc_connection); IRubyObject insert_key = runtime.getNil(); RubyClass resultClass = Result.createResultClass(runtime, moduleName, errorName, driver); // affectedCount == 1 means 1 updated row // or 1 row in result set that represents returned key (insert...returning), // other values represents numer of updated rows int affectedCount = 0; PreparedStatement sqlStatement = null; java.sql.ResultSet keys = null; // String sqlText = prepareSqlTextForPs(api.getInstanceVariable(recv, "@text").asJavaString(), // recv, args); String doSqlText = api.convertToRubyString(api.getInstanceVariable(recv, "@text")).getUnicodeValue(); String sqlText = prepareSqlTextForPs(doSqlText, recv, args); try { if (driver.supportsConnectionPrepareStatementMethodWithGKFlag()) { sqlStatement = conn.prepareStatement( sqlText, driver.supportsJdbcGeneratedKeys() ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); } else { // If java.sql.PreparedStatement#getGeneratedKeys() is not supported, // then it is important to call java.sql.Connection#prepareStatement(String) // -- with just a single parameter -- rather java.sql.Connection# // prepareStatement(String, int) (and passing in Statement.NO_GENERATED_KEYS). // Some less-than-complete JDBC drivers do not implement all of // the overloaded prepareStatement methods: the main culprit // being SQLiteJDBC which currently throws an ugly (and cryptic) // "NYI" SQLException if Connection#prepareStatement(String, int) // is called. sqlStatement = conn.prepareStatement(sqlText); } prepareStatementFromArgs(sqlStatement, recv, args); // javaConn.setAutoCommit(true); // hangs with autocommit set to false // sqlStatement.setMaxRows(); long startTime = System.currentTimeMillis(); try { if (sqlText.contains("RETURNING")) { keys = sqlStatement.executeQuery(); } else { affectedCount = sqlStatement.executeUpdate(); } } catch (SQLException sqle) { // This is to handle the edge case of SELECT sleep(1): // an executeUpdate() will throw a SQLException if a SELECT // is passed, so we try the same query again with execute() affectedCount = 0; sqlStatement.execute(); } long endTime = System.currentTimeMillis(); debug(recv.getRuntime(), driver.toString(sqlStatement), Long.valueOf(endTime - startTime)); if (keys == null) { if (driver.supportsJdbcGeneratedKeys()) { // Derby, H2, and MySQL all support getGeneratedKeys(), but only // to varying extents. // // However, javaConn.getMetaData().supportsGetGeneratedKeys() // currently returns FALSE for the Derby driver, as its support // is limited. As such, we use supportsJdbcGeneratedKeys() from // our own driver definition. // // See http://issues.apache.org/jira/browse/DERBY-242 // See http://issues.apache.org/jira/browse/DERBY-2631 // (Derby only supplies getGeneratedKeys() for auto-incremented // columns) // // apparently the prepared statements always provide the // generated keys keys = sqlStatement.getGeneratedKeys(); } else { // If there is no support, then a custom method can be defined // to return a ResultSet with keys keys = driver.getGeneratedKeys(conn); } } if (keys != null) { insert_key = unmarshal_id_result(runtime, keys); affectedCount = (affectedCount > 0) ? affectedCount : 1; } // not needed as it will be closed in the finally clause // sqlStatement.close(); // sqlStatement = null; } catch (SQLException sqle) { // TODO: log // sqle.printStackTrace(); throw newQueryError(runtime, sqle, sqlStatement); } finally { if (sqlStatement != null) { try { sqlStatement.close(); } catch (SQLException sqle2) { } } } // return nil if no updates are made if (affectedCount <= 0) { return runtime.getNil(); } IRubyObject affected_rows = runtime.newFixnum(affectedCount); IRubyObject result = api.callMethod(resultClass, "new", new IRubyObject[] {recv, affected_rows, insert_key}); return result; }
/** * @param args * @return */ @JRubyMethod(optional = 1, rest = true) public IRubyObject execute_non_query(IRubyObject[] args) { Ruby runtime = getRuntime(); Connection connection_instance = (Connection) api.getInstanceVariable(this, "@connection"); java.sql.Connection conn = connection_instance.getInternalConnection(); checkConnectionNotClosed(conn); IRubyObject insert_key = runtime.getNil(); RubyClass resultClass = Result.createResultClass(runtime, driver); // affectedCount == 1 means 1 updated row // or 1 row in result set that represents returned key (insert...returning), // other values represents number of updated rows int affectedCount = 0; PreparedStatement sqlStatement = null; // if usePreparedStatement returns false Statement sqlSimpleStatement = null; java.sql.ResultSet keys = null; // String sqlText = prepareSqlTextForPs(api.getInstanceVariable(recv, // "@text").asJavaString(), recv, args); String doSqlText = api.convertToRubyString(api.getInstanceVariable(this, "@text")).getUnicodeValue(); String sqlText = prepareSqlTextForPs(doSqlText, args); // additional callback for driver specific SQL statement changes sqlText = driver.prepareSqlTextForPs(sqlText, args); boolean usePS = usePreparedStatement(sqlText, args); boolean hasReturnParam = false; try { if (usePS) { if (driver.supportsConnectionPrepareStatementMethodWithGKFlag()) { sqlStatement = conn.prepareStatement( sqlText, driver.supportsJdbcGeneratedKeys() ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); } else { // If java.sql.PreparedStatement#getGeneratedKeys() is not supported, // then it is important to call java.sql.Connection#prepareStatement(String) // -- with just a single parameter -- rather java.sql.Connection# // prepareStatement(String, int) (and passing in Statement.NO_GENERATED_KEYS). // Some less-than-complete JDBC drivers do not implement all of // the overloaded prepareStatement methods: the main culprit // being SQLiteJDBC which currently throws an ugly (and cryptic) // "NYI" SQLException if Connection#prepareStatement(String, int) // is called. sqlStatement = conn.prepareStatement(sqlText); } hasReturnParam = prepareStatementFromArgs(sqlText, sqlStatement, args); } else { sqlSimpleStatement = conn.createStatement(); } long startTime = System.currentTimeMillis(); if (usePS) { boolean hasResult = sqlStatement.execute(); if (hasResult) { keys = sqlStatement.getResultSet(); } else { affectedCount = sqlStatement.getUpdateCount(); } } else { sqlSimpleStatement.execute(sqlText); } long endTime = System.currentTimeMillis(); if (usePS) debug(driver.statementToString(sqlStatement), Long.valueOf(endTime - startTime)); else debug(sqlText, Long.valueOf(endTime - startTime)); if (usePS && keys == null) { if (driver.supportsJdbcGeneratedKeys()) { // Derby, H2, and MySQL all support getGeneratedKeys(), but only // to varying extents. // // However, javaConn.getMetaData().supportsGetGeneratedKeys() // currently returns FALSE for the Derby driver, as its support // is limited. As such, we use supportsJdbcGeneratedKeys() from // our own driver definition. // // See http://issues.apache.org/jira/browse/DERBY-242 // See http://issues.apache.org/jira/browse/DERBY-2631 // (Derby only supplies getGeneratedKeys() for auto-incremented // columns) // // apparently the prepared statements always provide the // generated keys keys = sqlStatement.getGeneratedKeys(); } else if (hasReturnParam) { // Used in Oracle for INSERT ... RETURNING ... INTO ... statements insert_key = runtime.newFixnum(driver.getPreparedStatementReturnParam(sqlStatement)); } else { // If there is no support, then a custom method can be defined // to return a ResultSet with keys keys = driver.getGeneratedKeys(conn); } } if (usePS && keys != null) { insert_key = unmarshal_id_result(keys); if (insert_key != runtime.getNil()) affectedCount = (affectedCount > 0) ? affectedCount : 1; } } catch (SQLException sqle) { throw Errors.newQueryError(runtime, driver, sqle, usePS ? sqlStatement : sqlSimpleStatement); } finally { if (usePS) { JDBCUtil.close(keys, sqlStatement); } else { JDBCUtil.close(keys, sqlSimpleStatement); } keys = null; sqlStatement = null; sqlSimpleStatement = null; } IRubyObject affected_rows = runtime.newFixnum(affectedCount); return api.callMethod(resultClass, "new", new IRubyObject[] {this, affected_rows, insert_key}); }
private static IRubyObject number(Ruby runtime, int s) { RubyArray array = runtime.newArray(runtime.newFixnum(s)); return Pack.pack(runtime, array, FORMAT_SMALL_I); }
@JRubyMethod public IRubyObject parse(ThreadContext context, IRubyObject target) { Ruby runtime = context.runtime; // FIXME? only supports Unicode, since we have to produces strings... StreamReader reader; if (target.respondsTo("read")) { reader = new StreamReader(new InputStreamReader(new IOInputStream(target))); } else { reader = new StreamReader(new StringReader(target.convertToString().asJavaString())); } Parser parser = new ParserImpl(reader); IRubyObject handler = getInstanceVariable("@handler"); Event event; while (true) { try { event = parser.getEvent(); // FIXME: Event should expose a getID, so it can be switched if (event.is(ID.StreamStart)) { invoke(context, handler, "start_stream", runtime.newFixnum(YAML_ANY_ENCODING)); } else if (event.is(ID.DocumentStart)) { DocumentStartEvent dse = (DocumentStartEvent) event; Integer[] versionInts = dse.getVersion(); IRubyObject version = versionInts == null ? runtime.getNil() : RubyArray.newArray( runtime, runtime.newFixnum(versionInts[0]), runtime.newFixnum(versionInts[1])); Map<String, String> tagsMap = dse.getTags(); RubyArray tags = RubyArray.newArray(runtime); if (tags.size() > 0) { for (Map.Entry<String, String> tag : tagsMap.entrySet()) { tags.append( RubyArray.newArray( runtime, RubyString.newString(runtime, tag.getKey()), RubyString.newString(runtime, tag.getValue()))); } } invoke( context, handler, "start_document", version, tags, runtime.newBoolean(dse.getExplicit())); } else if (event.is(ID.DocumentEnd)) { DocumentEndEvent dee = (DocumentEndEvent) event; invoke(context, handler, "end_document", runtime.newBoolean(dee.getExplicit())); } else if (event.is(ID.Alias)) { AliasEvent ae = (AliasEvent) event; IRubyObject alias = runtime.getNil(); if (ae.getAnchor() != null) { alias = RubyString.newString(runtime, ae.getAnchor()); } invoke(context, handler, "alias", alias); } else if (event.is(ID.Scalar)) { ScalarEvent se = (ScalarEvent) event; IRubyObject anchor = se.getAnchor() == null ? runtime.getNil() : RubyString.newString(runtime, se.getAnchor()); IRubyObject tag = se.getTag() == null ? runtime.getNil() : RubyString.newString(runtime, se.getTag()); IRubyObject plain_implicit = runtime.newBoolean(se.getImplicit().isFirst()); IRubyObject quoted_implicit = runtime.newBoolean(se.getImplicit().isSecond()); IRubyObject style = runtime.newFixnum(se.getStyle()); IRubyObject val = RubyString.newString(runtime, se.getValue()); invoke( context, handler, "scalar", val, anchor, tag, plain_implicit, quoted_implicit, style); } else if (event.is(ID.SequenceStart)) { SequenceStartEvent sse = (SequenceStartEvent) event; IRubyObject anchor = sse.getAnchor() == null ? runtime.getNil() : RubyString.newString(runtime, sse.getAnchor()); IRubyObject tag = sse.getTag() == null ? runtime.getNil() : RubyString.newString(runtime, sse.getTag()); IRubyObject implicit = runtime.newBoolean(sse.getImplicit()); IRubyObject style = runtime.newFixnum(sse.getFlowStyle() ? 1 : 0); invoke(context, handler, "start_sequence", anchor, tag, implicit, style); } else if (event.is(ID.SequenceEnd)) { invoke(context, handler, "end_sequence"); } else if (event.is(ID.MappingStart)) { MappingStartEvent mse = (MappingStartEvent) event; IRubyObject anchor = mse.getAnchor() == null ? runtime.getNil() : RubyString.newString(runtime, mse.getAnchor()); IRubyObject tag = mse.getTag() == null ? runtime.getNil() : RubyString.newString(runtime, mse.getTag()); IRubyObject implicit = runtime.newBoolean(mse.getImplicit()); IRubyObject style = runtime.newFixnum(mse.getFlowStyle() ? 1 : 0); invoke(context, handler, "start_mapping", anchor, tag, implicit, style); } else if (event.is(ID.MappingEnd)) { invoke(context, handler, "end_mapping"); } else if (event.is(ID.StreamEnd)) { invoke(context, handler, "end_stream"); break; } } catch (ParserException pe) { parser = null; RubyKernel.raise( context, runtime.getModule("Psych").getConstant("SyntaxError"), new IRubyObject[] {runtime.newString(pe.getLocalizedMessage())}, Block.NULL_BLOCK); } } return this; }
public static final IRubyObject newUnsigned64(Ruby runtime, long value) { return value < 0 ? RubyBignum.newBignum( runtime, BigInteger.valueOf(value & 0x7fffffffffffffffL).add(UINT64_BASE)) : runtime.newFixnum(value); }
public static final IRubyObject newSigned64(Ruby runtime, long value) { return runtime.newFixnum(value); }
public static final IRubyObject newUnsigned32(Ruby runtime, int value) { return runtime.newFixnum(value < 0 ? (long) ((value & 0x7FFFFFFFL) + 0x80000000L) : value); }
public static final IRubyObject newSigned32(Ruby runtime, int value) { return runtime.newFixnum(value); }
@JRubyMethod(optional = 1, rest = true) public static IRubyObject execute_reader(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); IRubyObject connection_instance = api.getInstanceVariable(recv, "@connection"); IRubyObject wrapped_jdbc_connection = api.getInstanceVariable(connection_instance, "@connection"); if (wrapped_jdbc_connection.isNil()) { throw DataObjectsUtils.newDriverError( runtime, errorName, "This connection has already been closed."); } java.sql.Connection conn = getConnection(wrapped_jdbc_connection); RubyClass readerClass = Reader.createReaderClass(runtime, moduleName, errorName, driver); boolean inferTypes = false; int columnCount = 0; PreparedStatement sqlStatement = null; ResultSet resultSet = null; ResultSetMetaData metaData = null; // instantiate a new reader IRubyObject reader = readerClass.newInstance( runtime.getCurrentContext(), new IRubyObject[] {}, Block.NULL_BLOCK); // execute the query try { String sqlText = prepareSqlTextForPs(api.getInstanceVariable(recv, "@text").asJavaString(), recv, args); sqlStatement = conn.prepareStatement( sqlText, driver.supportsJdbcScrollableResultSets() ? ResultSet.TYPE_SCROLL_INSENSITIVE : ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); // sqlStatement.setMaxRows(); prepareStatementFromArgs(sqlStatement, recv, args); long startTime = System.currentTimeMillis(); resultSet = sqlStatement.executeQuery(); long endTime = System.currentTimeMillis(); debug(recv.getRuntime(), driver.toString(sqlStatement), Long.valueOf(endTime - startTime)); metaData = resultSet.getMetaData(); columnCount = metaData.getColumnCount(); // pass the response to the reader IRubyObject wrappedResultSet = Java.java_to_ruby(recv, JavaObject.wrap(recv.getRuntime(), resultSet), Block.NULL_BLOCK); reader.getInstanceVariables().setInstanceVariable("@reader", wrappedResultSet); wrappedResultSet.dataWrapStruct(resultSet); // handle each result // mark the reader as opened api.setInstanceVariable(reader, "@opened", runtime.newBoolean(true)); // TODO: if no response return nil api.setInstanceVariable(reader, "@position", runtime.newFixnum(0)); // save the field_count in reader api.setInstanceVariable(reader, "@field_count", runtime.newFixnum(columnCount)); // get the field types RubyArray field_names = runtime.newArray(); IRubyObject field_types = api.getInstanceVariable(recv, "@field_types"); // If no types are passed in, infer them if (field_types == null) { field_types = runtime.newArray(); inferTypes = true; } else { int fieldTypesCount = field_types.convertToArray().getLength(); if (field_types.isNil() || fieldTypesCount == 0) { field_types = runtime.newArray(); inferTypes = true; } else if (fieldTypesCount != columnCount) { // Wrong number of fields passed to set_types. Close the reader // and raise an error. api.callMethod(reader, "close"); throw runtime.newArgumentError( String.format( "Field-count mismatch. Expected %1$d fields, but the query yielded %2$d", fieldTypesCount, columnCount)); } } // for each field for (int i = 0; i < columnCount; i++) { RubyString field_name = runtime.newString(metaData.getColumnName(i + 1)); // infer the type if no types passed field_names.push_m(new IRubyObject[] {field_name}); if (inferTypes) { // TODO: do something } } // set the reader @field_names and @types (guessed or otherwise) api.setInstanceVariable(reader, "@fields", field_names); api.setInstanceVariable(reader, "@field_types", field_types); // keep the statement open // TODO why keep it open ??? // sqlStatement.close(); // sqlStatement = null; } catch (SQLException sqle) { // TODO: log sqle.printStackTrace(); throw newQueryError(runtime, sqle, sqlStatement); } finally { // if (sqlStatement != null) { // try { // sqlStatement.close(); // } catch (SQLException stsqlex) { // } // } } // return the reader return reader; }