Created
October 8, 2015 11:41
-
-
Save danielshaya/42b997ba661ca2c61942 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package chronicle.demo; | |
import net.openhft.chronicle.bytes.Bytes; | |
import net.openhft.chronicle.bytes.IORuntimeException; | |
import net.openhft.chronicle.wire.*; | |
import java.util.function.Function; | |
public class WireDemo { | |
public static void main(String[] args) { | |
System.out.println("-----------TEXT WIRE------------"); | |
Bytes serialisedBytes = serialise(b -> new TextWire(b), b -> b.toString()); | |
deserialise(new TextWire(serialisedBytes)); | |
System.out.println("-----------BINARY WIRE------------"); | |
serialisedBytes = serialise(b -> new BinaryWire(b), b -> b.toHexString()); | |
deserialise(new BinaryWire(serialisedBytes)); | |
System.out.println("-----------RAW WIRE------------"); | |
serialisedBytes = serialise(b -> new RawWire(b), b -> b.toHexString()); | |
deserialise(new RawWire(serialisedBytes)); | |
} | |
private static Bytes serialise(Function<Bytes, Wire> createWire, Function<Bytes, String> bytesToString) { | |
Bytes bytes = Bytes.elasticByteBuffer(); | |
Person person = new Person("dan", 44); | |
System.out.println("Person to serialise: " + person); | |
//This line serialises the person to Bytes using the wire implementation provided | |
person.writeMarshallable(createWire.apply(bytes)); | |
System.out.print("Wire prints:\n" + bytesToString.apply(bytes)); | |
return bytes; | |
} | |
private static void deserialise(Wire wire){ | |
Person person = new Person(); | |
//This line deserialises the Bytes (created in the serialise method) using | |
//the wire implementation provided. | |
person.readMarshallable(wire); | |
System.out.println("Deserialised person: " + person); | |
} | |
static class Person implements Marshallable{ | |
private String name; | |
private int age; | |
public Person(){ | |
} | |
public Person(String name, int age) { | |
this.name = name; | |
this.age = age; | |
} | |
@Override | |
public void readMarshallable(WireIn wireIn) throws IORuntimeException { | |
wireIn.read(() -> "name").text(this, (o, b) -> o.name = b) | |
.read(() -> "age").int8(this, (o, b) -> o.age = b); | |
} | |
@Override | |
public void writeMarshallable(WireOut wireOut) { | |
wireOut.write(() -> "name").text(name) | |
.write(() -> "age").int8(age); | |
} | |
@Override | |
public String toString() { | |
return "Person{" + | |
"name='" + name + '\'' + | |
", age=" + age + | |
'}'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment