Example: manipulating data
This page contains examples of basic data manipulation using a combination of JavaScript and Java.
Convert a byte array to a string, and back
This example is for a MongoDB listener, but can easily be adapted to other environments. In this case, the packet object is a JSON object with an attribute called payload which contains a byte array.
var doc = context.packet.getDocumentJson(0);
const JavaString = Java.type("java.lang.String");
var payload = new JavaString(doc.payload);
// And back to bytes
let stringBytes = payload.getBytes();
In some cases, this may fail because the String constructor is ambiguous. In that case, you can use the BSONUtil class:
var doc = context.packet.getDocumentJson(0);
const BSONUtil = Java.type("com.galliumdata.server.handler.mongo.BSONUtil");
var payload = BSONUtil.createStringFromBytes(doc.payload);