Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a serialized object to appengine java task?

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.

like image 212
aloo Avatar asked Mar 20 '10 21:03

aloo


2 Answers

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

like image 167
Uri Lukach Avatar answered Oct 05 '22 22:10

Uri Lukach


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.

like image 22
msw Avatar answered Oct 06 '22 00:10

msw