Skip to content

Commit

Permalink
feat: SerializeExample
Browse files Browse the repository at this point in the history
  • Loading branch information
killme2008 committed Oct 3, 2023
1 parent 95f499f commit d67a202
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/test/java/com/googlecode/aviator/example/SerializeExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.googlecode.aviator.example;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.AviatorEvaluatorInstance;
import com.googlecode.aviator.Expression;
import com.googlecode.aviator.Options;

/**
* Demo for expression serialization
*
* @author dennis
*
*/
public class SerializeExample {

public static void main(String[] args) throws Exception {
// Enable expression serialization feature
AviatorEvaluatorInstance engine = AviatorEvaluator.getInstance();
engine.setOption(Options.SERIALIZABLE, true);

Expression exp = engine.compile("if (a>b) { return a; } else { return b; }");

// Execute the raw expression
Object result = exp.execute(exp.newEnv("a", 42, "b", 99));
System.out.println("Raw expression result:" + result);

// Serialize the expression
byte[] bs = null; // the serialized bytes
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
// Create the ObjectOutputStream
ObjectOutputStream output = engine.newObjectOutputStream(out);
// Write the expression object
output.writeObject(exp);
output.close();
// Get the result byte array
bs = out.toByteArray();
}

System.out.println("Serialize expression bytes array length: " + bs.length);

// Deserialize expression from bytes
try (ByteArrayInputStream in = new ByteArrayInputStream(bs)) {
// Create the ObjectInputStream from ByteArrayInputStream(bs)
ObjectInputStream input = engine.newObjectInputStream(in);
// Read the expression from ObjectInputStream
Expression newExp = (Expression) input.readObject();
// Execute the expression
result = newExp.execute(newExp.newEnv("a", 42, "b", 99));
System.out.println("Deserialized expression result:" + result);
}
}

}

0 comments on commit d67a202

Please sign in to comment.