Reputation: 32627
I am trying to optimize the following code which is used to produce a stream containing random data of a given length that is streamed from the server to the client:
@GET
@Path("/foo/....")
public Response download(...)
throws IOException
{
...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// This method writes some random bytes to a stream.
generateRandomData(baos, resource.length());
System.out.println("Generated stream with " +
baos.toByteArray().length +
" bytes.");
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return Response.ok(is).build();
}
The code above look ridiculous as it won't work for large data, I know, but I haven't found a better method for writing to the stream of the response. Could somebody please show me the proper way of doing it?
Many thanks in advance!
Upvotes: 3
Views: 5725
Reputation: 2563
Create your own InputStream implementation defining read
method to return random data :
public class RandomInputStream
extends InputStream
{
private long count;
private long length;
private Random random = new Random();
public RandomInputStream(long length)
{
super();
this.length = length;
}
@Override
public int read()
throws IOException
{
if (count >= length)
{
return -1;
}
count++;
return random.nextInt();
}
public long getCount()
{
return count;
}
public void setCount(long count)
{
this.count = count;
}
public long getLength()
{
return length;
}
public void setLength(long length)
{
this.length = length;
}
}
Upvotes: 2