TIBCO Spotfire® Statistics Services Users Guide

Creating a binary serialization request for R using Java and rJava

The example described in this topic uses example test code in the Java API and the rJava package to demonstrate how one might build a request using the binary API.

Procedure

  1. Create an object and then serialize the object using R serialization.
  2. Invoke the Java API eval method to create and send to the server a synchronous job request. (This eval method can accept binary arguments (that is, a BinaryArgument object).
  3. The request is sent to the server, processed in the R engine there, and the results are returned (serialized and deserialized as needed).
  4. The results are returned as a serialized byte array.

Example

public void PassBinaryArgument() throws Exception {
    //Serialize an object using TERR serialization.
    byte[] asByteArray = getSerializedBytes("1:10");
    // Invoke the overloaded eval method that accepts
    // and returns binary arguments.
    SplusDataResult result = mApi.eval("as.integer((x+1))",
        new SynchronousJobStartup(), new BinaryDataRequest(
        new BinaryArgument("x", asByteArray,
            SerializationType.RSerialize)));
 // NOTE: The following code uses the rJava library,
 // which includes rengine and its eval method (NOT to
 // be confused with the eval method found in the
 // Spotfire Statistics Services Java APIs.
protected byte[] getSerializedBytes(String expression) {
    rengine.eval("a<-serialize(" + expression + ",NULL)");
    rengine.eval(
        ".jcall('com/insightful/splusserver/r/binary/
        RBinaryArgumentExample'," + 
        "'V','setA',a)");
    return serializedArray;
}
protected REXP unserializeInREngine(byte[] serializedData) {
    serializedArray = serializedData;
    rengine.eval("a<-.jcall('com/insightful/splusserver/
        r/binary/RBinaryArgumentExample'," +
        "'[B','getA')");
    return rengine.eval("unserialize(a)");
}
private static byte[] serializedArray;
public static void setA(byte[] a) {
        serializedArray = a;
}
public static byte[] getA() {
    return serializedArray;
}
Note: The above shows just the relevant sections. Note that it uses the rJava package to transfer data between Java and R, so it is necessary to have knowledge of rJava to write such code.