1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.codec.delimited.serialization;
21
22 import java.io.InputStream;
23 import java.lang.reflect.Method;
24
25 import org.apache.mina.codec.IoBuffer;
26 import org.apache.mina.codec.ProtocolDecoderException;
27 import org.apache.mina.codec.delimited.IoBufferDecoder;
28
29 import com.google.protobuf.ExtensionRegistryLite;
30 import com.google.protobuf.GeneratedMessage;
31
32
33
34
35 public final class ProtobufMessageDecoder<IN extends GeneratedMessage> extends IoBufferDecoder<IN> {
36 private final Method parseMethod;
37
38 private final ExtensionRegistryLite registry;
39
40 public static <TYPE extends GeneratedMessage> ProtobufMessageDecoder<TYPE> newInstance(Class<TYPE> c)
41 throws NoSuchMethodException {
42 return newInstance(c, ExtensionRegistryLite.getEmptyRegistry());
43 }
44
45 public static <TYPE extends GeneratedMessage> ProtobufMessageDecoder<TYPE> newInstance(Class<TYPE> c,
46 ExtensionRegistryLite registry) throws NoSuchMethodException {
47 return new ProtobufMessageDecoder<TYPE>(c, registry);
48 }
49
50 private ProtobufMessageDecoder(Class<IN> clazz, ExtensionRegistryLite registry) throws NoSuchMethodException {
51 super();
52 parseMethod = clazz.getDeclaredMethod("parseFrom", InputStream.class, ExtensionRegistryLite.class);
53 this.registry = registry;
54 }
55
56 @SuppressWarnings("unchecked")
57 @Override
58 public IN decode(IoBuffer input) {
59 try {
60 return (IN) parseMethod.invoke(null, input.asInputStream(), registry);
61 } catch (Exception e) {
62 throw new ProtocolDecoderException(e);
63 }
64 }
65 }