ConformanceJava.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import com.google.protobuf.ByteString;
  2. import com.google.protobuf.CodedInputStream;
  3. import com.google.protobuf.conformance.Conformance;
  4. import com.google.protobuf.InvalidProtocolBufferException;
  5. import com.google.protobuf_test_messages.proto3.TestMessagesProto3;
  6. import com.google.protobuf.util.JsonFormat;
  7. import com.google.protobuf.util.JsonFormat.TypeRegistry;
  8. import java.io.IOException;
  9. import java.nio.ByteBuffer;
  10. class ConformanceJava {
  11. private int testCount = 0;
  12. private TypeRegistry typeRegistry;
  13. private boolean readFromStdin(byte[] buf, int len) throws Exception {
  14. int ofs = 0;
  15. while (len > 0) {
  16. int read = System.in.read(buf, ofs, len);
  17. if (read == -1) {
  18. return false; // EOF
  19. }
  20. ofs += read;
  21. len -= read;
  22. }
  23. return true;
  24. }
  25. private void writeToStdout(byte[] buf) throws Exception {
  26. System.out.write(buf);
  27. }
  28. // Returns -1 on EOF (the actual values will always be positive).
  29. private int readLittleEndianIntFromStdin() throws Exception {
  30. byte[] buf = new byte[4];
  31. if (!readFromStdin(buf, 4)) {
  32. return -1;
  33. }
  34. return (buf[0] & 0xff)
  35. | ((buf[1] & 0xff) << 8)
  36. | ((buf[2] & 0xff) << 16)
  37. | ((buf[3] & 0xff) << 24);
  38. }
  39. private void writeLittleEndianIntToStdout(int val) throws Exception {
  40. byte[] buf = new byte[4];
  41. buf[0] = (byte)val;
  42. buf[1] = (byte)(val >> 8);
  43. buf[2] = (byte)(val >> 16);
  44. buf[3] = (byte)(val >> 24);
  45. writeToStdout(buf);
  46. }
  47. private enum BinaryDecoder {
  48. BYTE_STRING_DECODER() {
  49. @Override
  50. public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
  51. throws InvalidProtocolBufferException {
  52. return TestMessagesProto3.TestAllTypes.parseFrom(bytes);
  53. }
  54. },
  55. BYTE_ARRAY_DECODER() {
  56. @Override
  57. public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
  58. throws InvalidProtocolBufferException {
  59. return TestMessagesProto3.TestAllTypes.parseFrom(bytes.toByteArray());
  60. }
  61. },
  62. ARRAY_BYTE_BUFFER_DECODER() {
  63. @Override
  64. public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
  65. throws InvalidProtocolBufferException {
  66. ByteBuffer buffer = ByteBuffer.allocate(bytes.size());
  67. bytes.copyTo(buffer);
  68. buffer.flip();
  69. try {
  70. return TestMessagesProto3.TestAllTypes.parseFrom(CodedInputStream.newInstance(buffer));
  71. } catch (InvalidProtocolBufferException e) {
  72. throw e;
  73. } catch (IOException e) {
  74. throw new RuntimeException(
  75. "ByteString based ByteBuffer should not throw IOException.", e);
  76. }
  77. }
  78. },
  79. READONLY_ARRAY_BYTE_BUFFER_DECODER() {
  80. @Override
  81. public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
  82. throws InvalidProtocolBufferException {
  83. try {
  84. return TestMessagesProto3.TestAllTypes.parseFrom(
  85. CodedInputStream.newInstance(bytes.asReadOnlyByteBuffer()));
  86. } catch (InvalidProtocolBufferException e) {
  87. throw e;
  88. } catch (IOException e) {
  89. throw new RuntimeException(
  90. "ByteString based ByteBuffer should not throw IOException.", e);
  91. }
  92. }
  93. },
  94. DIRECT_BYTE_BUFFER_DECODER() {
  95. @Override
  96. public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
  97. throws InvalidProtocolBufferException {
  98. ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size());
  99. bytes.copyTo(buffer);
  100. buffer.flip();
  101. try {
  102. return TestMessagesProto3.TestAllTypes.parseFrom(CodedInputStream.newInstance(buffer));
  103. } catch (InvalidProtocolBufferException e) {
  104. throw e;
  105. } catch (IOException e) {
  106. throw new RuntimeException(
  107. "ByteString based ByteBuffer should not throw IOException.", e);
  108. }
  109. }
  110. },
  111. READONLY_DIRECT_BYTE_BUFFER_DECODER() {
  112. @Override
  113. public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
  114. throws InvalidProtocolBufferException {
  115. ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size());
  116. bytes.copyTo(buffer);
  117. buffer.flip();
  118. try {
  119. return TestMessagesProto3.TestAllTypes.parseFrom(
  120. CodedInputStream.newInstance(buffer.asReadOnlyBuffer()));
  121. } catch (InvalidProtocolBufferException e) {
  122. throw e;
  123. } catch (IOException e) {
  124. throw new RuntimeException(
  125. "ByteString based ByteBuffer should not throw IOException.", e);
  126. }
  127. }
  128. },
  129. INPUT_STREAM_DECODER() {
  130. @Override
  131. public TestMessagesProto3.TestAllTypes parse(ByteString bytes)
  132. throws InvalidProtocolBufferException {
  133. try {
  134. return TestMessagesProto3.TestAllTypes.parseFrom(bytes.newInput());
  135. } catch (InvalidProtocolBufferException e) {
  136. throw e;
  137. } catch (IOException e) {
  138. throw new RuntimeException(
  139. "ByteString based InputStream should not throw IOException.", e);
  140. }
  141. }
  142. };
  143. public abstract TestMessagesProto3.TestAllTypes parse(ByteString bytes)
  144. throws InvalidProtocolBufferException;
  145. }
  146. private TestMessagesProto3.TestAllTypes parseBinary(ByteString bytes)
  147. throws InvalidProtocolBufferException {
  148. TestMessagesProto3.TestAllTypes[] messages =
  149. new TestMessagesProto3.TestAllTypes[BinaryDecoder.values().length];
  150. InvalidProtocolBufferException[] exceptions =
  151. new InvalidProtocolBufferException[BinaryDecoder.values().length];
  152. boolean hasMessage = false;
  153. boolean hasException = false;
  154. for (int i = 0; i < BinaryDecoder.values().length; ++i) {
  155. try {
  156. messages[i] = BinaryDecoder.values()[i].parse(bytes);
  157. hasMessage = true;
  158. } catch (InvalidProtocolBufferException e) {
  159. exceptions[i] = e;
  160. hasException = true;
  161. }
  162. }
  163. if (hasMessage && hasException) {
  164. StringBuilder sb =
  165. new StringBuilder("Binary decoders disagreed on whether the payload was valid.\n");
  166. for (int i = 0; i < BinaryDecoder.values().length; ++i) {
  167. sb.append(BinaryDecoder.values()[i].name());
  168. if (messages[i] != null) {
  169. sb.append(" accepted the payload.\n");
  170. } else {
  171. sb.append(" rejected the payload.\n");
  172. }
  173. }
  174. throw new RuntimeException(sb.toString());
  175. }
  176. if (hasException) {
  177. // We do not check if exceptions are equal. Different implementations may return different
  178. // exception messages. Throw an arbitrary one out instead.
  179. throw exceptions[0];
  180. }
  181. // Fast path comparing all the messages with the first message, assuming equality being
  182. // symmetric and transitive.
  183. boolean allEqual = true;
  184. for (int i = 1; i < messages.length; ++i) {
  185. if (!messages[0].equals(messages[i])) {
  186. allEqual = false;
  187. break;
  188. }
  189. }
  190. // Slow path: compare and find out all unequal pairs.
  191. if (!allEqual) {
  192. StringBuilder sb = new StringBuilder();
  193. for (int i = 0; i < messages.length - 1; ++i) {
  194. for (int j = i + 1; j < messages.length; ++j) {
  195. if (!messages[i].equals(messages[j])) {
  196. sb.append(BinaryDecoder.values()[i].name())
  197. .append(" and ")
  198. .append(BinaryDecoder.values()[j].name())
  199. .append(" parsed the payload differently.\n");
  200. }
  201. }
  202. }
  203. throw new RuntimeException(sb.toString());
  204. }
  205. return messages[0];
  206. }
  207. private Conformance.ConformanceResponse doTest(Conformance.ConformanceRequest request) {
  208. TestMessagesProto3.TestAllTypes testMessage;
  209. switch (request.getPayloadCase()) {
  210. case PROTOBUF_PAYLOAD: {
  211. try {
  212. testMessage = parseBinary(request.getProtobufPayload());
  213. } catch (InvalidProtocolBufferException e) {
  214. return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build();
  215. }
  216. break;
  217. }
  218. case JSON_PAYLOAD: {
  219. try {
  220. TestMessagesProto3.TestAllTypes.Builder builder = TestMessagesProto3.TestAllTypes.newBuilder();
  221. JsonFormat.parser().usingTypeRegistry(typeRegistry)
  222. .merge(request.getJsonPayload(), builder);
  223. testMessage = builder.build();
  224. } catch (InvalidProtocolBufferException e) {
  225. return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build();
  226. }
  227. break;
  228. }
  229. case PAYLOAD_NOT_SET: {
  230. throw new RuntimeException("Request didn't have payload.");
  231. }
  232. default: {
  233. throw new RuntimeException("Unexpected payload case.");
  234. }
  235. }
  236. switch (request.getRequestedOutputFormat()) {
  237. case UNSPECIFIED:
  238. throw new RuntimeException("Unspecified output format.");
  239. case PROTOBUF:
  240. return Conformance.ConformanceResponse.newBuilder().setProtobufPayload(testMessage.toByteString()).build();
  241. case JSON:
  242. try {
  243. return Conformance.ConformanceResponse.newBuilder().setJsonPayload(
  244. JsonFormat.printer().usingTypeRegistry(typeRegistry).print(testMessage)).build();
  245. } catch (InvalidProtocolBufferException | IllegalArgumentException e) {
  246. return Conformance.ConformanceResponse.newBuilder().setSerializeError(
  247. e.getMessage()).build();
  248. }
  249. default: {
  250. throw new RuntimeException("Unexpected request output.");
  251. }
  252. }
  253. }
  254. private boolean doTestIo() throws Exception {
  255. int bytes = readLittleEndianIntFromStdin();
  256. if (bytes == -1) {
  257. return false; // EOF
  258. }
  259. byte[] serializedInput = new byte[bytes];
  260. if (!readFromStdin(serializedInput, bytes)) {
  261. throw new RuntimeException("Unexpected EOF from test program.");
  262. }
  263. Conformance.ConformanceRequest request =
  264. Conformance.ConformanceRequest.parseFrom(serializedInput);
  265. Conformance.ConformanceResponse response = doTest(request);
  266. byte[] serializedOutput = response.toByteArray();
  267. writeLittleEndianIntToStdout(serializedOutput.length);
  268. writeToStdout(serializedOutput);
  269. return true;
  270. }
  271. public void run() throws Exception {
  272. typeRegistry = TypeRegistry.newBuilder().add(
  273. TestMessagesProto3.TestAllTypes.getDescriptor()).build();
  274. while (doTestIo()) {
  275. this.testCount++;
  276. }
  277. System.err.println("ConformanceJava: received EOF from test runner after " +
  278. this.testCount + " tests");
  279. }
  280. public static void main(String[] args) throws Exception {
  281. new ConformanceJava().run();
  282. }
  283. }