A blog about software development and other software related matters

Blog Archive

Sunday, June 1, 2008

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 << String.from_java_bytes(bytes)
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!!! :)

No comments: