org.mydotey.codec.probotuf.ProtoMessageCodec Maven / Gradle / Ivy
The newest version!
package org.mydotey.codec.probotuf;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.mydotey.codec.CodecException;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.Parser;
@SuppressWarnings("unchecked")
public class ProtoMessageCodec extends ProtobufCodec {
public static final ProtoMessageCodec DEFAULT = new ProtoMessageCodec();
public ProtoMessageCodec() {
}
@Override
protected byte[] doEncode(Object obj) {
Message message = (Message) obj;
return message.toByteArray();
}
@Override
protected T doDecode(byte[] is, Class clazz) {
Parser parser = getParser(clazz);
try {
return (T) parser.parseFrom(is);
} catch (InvalidProtocolBufferException e) {
throw new CodecException(e);
}
}
@Override
protected void doEncode(OutputStream os, Object obj) {
try {
Message message = (Message) obj;
message.writeTo(os);
} catch (IOException e) {
throw new CodecException(e);
}
}
@Override
protected T doDecode(InputStream is, Class clazz) {
Parser parser = getParser(clazz);
try {
return (T) parser.parseFrom(is);
} catch (InvalidProtocolBufferException e) {
throw new CodecException(e);
}
}
protected Parser getParser(Class clazz) {
try {
Method method = clazz.getMethod("parser");
return (Parser) method.invoke(null);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new CodecException(
"clazz must be a Google PB Message & has an auto generated public static method parser()", e);
}
}
}