Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RayRoestenburg/316198 to your computer and use it in GitHub Desktop.
Save RayRoestenburg/316198 to your computer and use it in GitHub Desktop.
encode decode bson
package my.gists.test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import junit.framework.Assert;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.ByteDecoder;
import com.mongodb.ByteEncoder;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
/**
* Simple and naive little test to check out the BSON encoder and decoder.
*
* @author Raymond Roestenburg
*
*/
public class BSONTest {
private BasicDBObject doc;
public BSONTest() {
// create a BSON document
doc = new BasicDBObject();
doc.put("name", "MongoDB");
doc.put("type", "database");
doc.put("count", 1);
}
/**
* Naive test for encoding and decoding a BSON message
*/
@Test
public void should_encode_and_decode_simple_BSON_message() {
ByteBuffer b = encode(doc);
DBObject decoded = decode(b);
// check it
assertDoc(decoded);
}
@Test
public void should_encode_and_decode_simple_JSON_to_BSON() {
String json = "{ \"name\" : \"MongoDB\" , \"type\" : \"database\" , \"count\" : 1}";
DBObject parsedDoc = (DBObject) JSON.parse(json);
assertDoc(parsedDoc);
ByteBuffer buf = encode(parsedDoc);
DBObject decodedObject = decode(buf);
assertDoc(decodedObject);
String jsonResult = JSON.serialize(decodedObject);
Assert.assertEquals(jsonResult, json);
}
private void assertDoc(DBObject returned) {
Assert.assertEquals("MongoDB", returned.get("name"));
Assert.assertEquals("database", returned.get("type"));
Assert.assertEquals(1, returned.get("count"));
}
private ByteBuffer encode(DBObject dbObject) {
// encode one single document
ByteEncoder encoder = ByteEncoder.get();
encoder.putObject(dbObject);
// get the result from the encoder
byte[] bytes = encoder.getBytes();
ByteBuffer buf = ByteBuffer.allocate(bytes.length);
// BSON is in little endian byte order. put it in a buffer
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.put(bytes);
buf.rewind();
return buf;
}
private DBObject decode(ByteBuffer b) {
// decode de BSON message
ByteDecoder decoder = new ByteDecoder(b);
return decoder.readObject();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment