views:

170

answers:

2

Hi all,

I'm using java appengine and the task queue API to run async tasks. I would like to add a task to the task queue but pass a a java object as a parameter. I notic the task options api can add a parameter as a byte[] but I'm unsure how to use it.

1) How would I serialize my object to a byte[]? and 2) How would the task read the byte[] and reconstruct the original object?

Thanks.

A: 

Turning objects into sequences of bytes and vice versa is what Serializable is made for. In the simple case, a Java class is made serializable by merely declaring it implements Serializable.

The serialization of an object is based around introspection where the serialization code looks at the data of the serializable class and packages them in a way that describes the structure and data. Since the data stream contains the information needed to reconstruct the entire object, that's what the receiving side does.

You could look at the gory details by wrapping an ObjectOuputStream around a ByteArrayOutputStream, write an object to that and look at the underlying string, but you'd probably find the Object Serialization page more informative.

msw
Thanks for the link - I've managed to get an object written out to a byte stream (and then to a byte array). However, I can't figure out how to read from a byte array and reconstruct the object. Any ideas?Also, any thoughts on how this works with the appengine task queue api? I can pass, as a parameter to a task, a byte[]. However, I'm unclear how to get the byte array from the parameter map when the task runs.
aloo
The object reconstruction is handled by ObjectInputStream.http://java.sun.com/javase/6/docs/api/java/io/ObjectInputStream.html
msw
A: 

Hey,

You have a few techniques to deliver the byte stream using Queue API,

  1. Using TaskOptions.payload method

  2. Using TaskOptions.params method

I will demonstrate how to write & read the byte stream information since there are some minor issues with google appengine implementation :)

Writing the bytes:

// task is an instance of TaskOptions // Base64 - Apache implementation is being used here to encode bytes as base 64 // taskBytes - your serialized bytes

task.param("Enter-Parameter-Name", Base64.encodeBase64(taskBytes));

Reading the bytes:

// Base64 - Apache implementation is being used here to encode bytes as base 64

byte[] questionsBytes = Base64.decodeBase64(request.getParameter("Enter-Parameter-Name").getBytes());

This solution works fine for me.

All the Best Uri

Uri Lukach