Narkisr - blog

Narkisr.com where code writes itself.


02
Jun 8

JRuby and the pittfalls of bytes

JRuby is an amazing environment to code in, you can get clean concise and elegant Java based code by using Ruby powerful constructs, like for example:
JBIStream=java.io.BufferedInputStream

def read_body_as_stream(method)
 bis = JBIStream.new( method.responseBodyAsStream())
 res = ''
 bytes=Java::byte[8192].new # creating new Java byte primitive array
 count = bis.read( bytes )
 while( count != -1)
  res
  count = bis.read(bytes);
 end
 bis.close()
 res
end

This code basically takes in an Apache commons http method and extracts its body by using its input stream, well almost!
This code contains a nasty and confusing bug, the String.from_java_bytes(bytes) chews up dirty bits on each iteration from its previous one, the soultion:
    res << String.from_java_bytes(bytes)[0,count]

The joy of bytes!!! :)


This website content by Ronen Narkis is licensed under a Creative Commons Attribution 2.5 Israel License, based on a work at narkisr.com, Permissions beyond the scope of this license may be available at narkisr.com.