Skip to content

Instantly share code, notes, and snippets.

@kmaehashi
Last active December 10, 2015 03:08
Show Gist options
  • Save kmaehashi/4372613 to your computer and use it in GitHub Desktop.
Save kmaehashi/4372613 to your computer and use it in GitHub Desktop.
オシャレタプル for MessagePack-Java
public class ClassifierClient {
private static class TupleMessagePack extends MessagePack {
protected TupleMessagePack(TemplateRegistry registry) {
super(registry);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static MessagePack get() {
TemplateRegistry reg = new TemplateRegistry(null);
AnyTemplate any = new AnyTemplate(reg);
reg.register(Tuple.class, new Tuple.TupleTemplate(any, any));
reg.registerGeneric(Tuple.class, new GenericMapTemplate(reg,
Tuple.TupleTemplate.class));
return new TupleMessagePack(reg);
}
}
public ClassifierClient(String host, int port, double timeout_sec)
throws Exception {
EventLoop loop = EventLoop.start(TupleMessagePack.get());
c_ = new Client(host, port, loop);
iface_ = c_.proxy(RPCInterface.class);
}
// ... snip ...
}
import java.io.IOException;
import org.msgpack.MessageTypeException;
import org.msgpack.annotation.Message;
import org.msgpack.packer.Packer;
import org.msgpack.template.AbstractTemplate;
import org.msgpack.template.Template;
import org.msgpack.unpacker.Unpacker;
@Message
public class Tuple<E1, E2> {
public E1 first;
public E2 second;
public Tuple() {
}
public Tuple(E1 first, E2 second) {
this.first = first;
this.second = second;
}
static class TupleTemplate<E1, E2> extends AbstractTemplate<Tuple<E1, E2>> {
private Template<E1> e1Template;
private Template<E2> e2Template;
public TupleTemplate(Template<E1> e1Template, Template<E2> e2Template) {
this.e1Template = e1Template;
this.e2Template = e2Template;
}
public void write(Packer pk, Tuple<E1, E2> target, boolean required)
throws IOException {
if (target == null) {
if (required) {
throw new MessageTypeException("Attempted to write null");
}
pk.writeNil();
return;
}
pk.writeArrayBegin(2);
e1Template.write(pk, target.first);
e2Template.write(pk, target.second);
pk.writeArrayEnd();
}
public Tuple<E1, E2> read(Unpacker u, Tuple<E1, E2> to, boolean required)
throws IOException {
if (!required && u.trySkipNil()) {
return null;
}
int n = u.readArrayBegin();
if (n != 2) {
throw new MessageTypeException(
"Invalid number of elements: expected 2 but got " + n);
}
Tuple<E1, E2> tuple = to;
if (tuple == null) {
tuple = new Tuple<E1, E2>();
}
tuple.first = e1Template.read(u, null);
tuple.second = e2Template.read(u, null);
u.readArrayEnd();
return tuple;
}
}
}
// Java 6
Tuple<String, Datum> train_datum = new Tuple<String, Datum>("japanese", datum);
// Java 7 だと、こう書ける!
Tuple<String, Datum> train_datum = new Tuple<>("japanese", datum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment