Tuesday, July 20, 2010

Dilbert's Salary Theorem - Proved

THEOREM

Dilbert's "Salary Theorem" states that:
"Engineers and scientists can never earn as much as business executives and sales people."

This theorem can now be supported by a mathematical equation based on the following two postulates:
1. Knowledge is Power.
2. Time is Money.

As every engineer knows: Power = Work / Time
Since: Knowledge = Power, and Time = Money, then Knowledge = Work / Money
Solving for Money, we get: Money = Work / Knowledge

Thus, as Knowledge approaches zero, Money approaches infinity, regardless of the amount of work done.

Conclusion: The less you know, the more you make.

QED.

Wednesday, May 12, 2010

Object serialization and GSON to/from JSON

If you have a serializable java object and want to ship it over to another server than you may want to consider using GSON/JSON. I ran into an issue where a complex serializable object would not convert to JSON using GSON.TOJSON method.

so, I used the old trick in the book. For the sake of discussion assume that "SomeObject" is the java object which needs to be shipped as JSON back and forth client/server

on the client side

Step 1. convert the java object to byte[] (serialization)



ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(SomeObjectTobeSerialized);
oos.close();
baos.toByteArray();


Step 2. use GSON.toJSON. This shall convert the byte[] to JSONArray.

JSONObject json = new JSONObject();
json.put("BODY", serializeObject(SomeObject)); // serializeObject is the method whose body is Step 1 above


Now, send the JSON over to server via any of your favorite mechanism.

one the server side

Step 1. read the JSON from the request (HttpServletReq) object


StringBuilder sb = new StringBuilder();
BufferedReader reader = req.getReader();
String inputLine;
while ((inputLine = reader.readLine()) != null) {
sb.append(inputLine);
}

JSONObject jsonRequest = new JSONObject(sb.toString());


Step2. deserialize JSONArray sent over by client

JSONArray serializedObject = jsonRequest.get("BODY")
byte[] bytes = new byte[serializedObject.length()];
InputStream is = null;
ObjectInputStream ois = null;
SomeObject str = null;
try {
int read = 0;
while (read < bytes.length) {
bytes[read] = (byte)serializedObject.getInt(read);
read++;
}
is = new ByteArrayInputStream(bytes);


ois = new ObjectInputStream(is);
str= (SomeObject) ois.readObject();


So, you get "SomeObject" back deserialized and intact.