ConformanceJava.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. import com.google.protobuf.AbstractMessage;
  31. import com.google.protobuf.ByteString;
  32. import com.google.protobuf.CodedInputStream;
  33. import com.google.protobuf.ExtensionRegistry;
  34. import com.google.protobuf.InvalidProtocolBufferException;
  35. import com.google.protobuf.Parser;
  36. import com.google.protobuf.TextFormat;
  37. import com.google.protobuf.conformance.Conformance;
  38. import com.google.protobuf.util.JsonFormat;
  39. import com.google.protobuf.util.JsonFormat.TypeRegistry;
  40. import com.google.protobuf_test_messages.proto2.TestMessagesProto2;
  41. import com.google.protobuf_test_messages.proto2.TestMessagesProto2.TestAllTypesProto2;
  42. import com.google.protobuf_test_messages.proto3.TestMessagesProto3;
  43. import com.google.protobuf_test_messages.proto3.TestMessagesProto3.TestAllTypesProto3;
  44. import java.nio.ByteBuffer;
  45. import java.util.ArrayList;
  46. class ConformanceJava {
  47. private int testCount = 0;
  48. private TypeRegistry typeRegistry;
  49. private boolean readFromStdin(byte[] buf, int len) throws Exception {
  50. int ofs = 0;
  51. while (len > 0) {
  52. int read = System.in.read(buf, ofs, len);
  53. if (read == -1) {
  54. return false; // EOF
  55. }
  56. ofs += read;
  57. len -= read;
  58. }
  59. return true;
  60. }
  61. private void writeToStdout(byte[] buf) throws Exception {
  62. System.out.write(buf);
  63. }
  64. // Returns -1 on EOF (the actual values will always be positive).
  65. private int readLittleEndianIntFromStdin() throws Exception {
  66. byte[] buf = new byte[4];
  67. if (!readFromStdin(buf, 4)) {
  68. return -1;
  69. }
  70. return (buf[0] & 0xff)
  71. | ((buf[1] & 0xff) << 8)
  72. | ((buf[2] & 0xff) << 16)
  73. | ((buf[3] & 0xff) << 24);
  74. }
  75. private void writeLittleEndianIntToStdout(int val) throws Exception {
  76. byte[] buf = new byte[4];
  77. buf[0] = (byte)val;
  78. buf[1] = (byte)(val >> 8);
  79. buf[2] = (byte)(val >> 16);
  80. buf[3] = (byte)(val >> 24);
  81. writeToStdout(buf);
  82. }
  83. private enum BinaryDecoderType {
  84. BTYE_STRING_DECODER,
  85. BYTE_ARRAY_DECODER,
  86. ARRAY_BYTE_BUFFER_DECODER,
  87. READONLY_ARRAY_BYTE_BUFFER_DECODER,
  88. DIRECT_BYTE_BUFFER_DECODER,
  89. READONLY_DIRECT_BYTE_BUFFER_DECODER,
  90. INPUT_STREAM_DECODER;
  91. }
  92. private static class BinaryDecoder <MessageType extends AbstractMessage> {
  93. public MessageType decode (ByteString bytes, BinaryDecoderType type,
  94. Parser <MessageType> parser, ExtensionRegistry extensions)
  95. throws InvalidProtocolBufferException {
  96. switch (type) {
  97. case BTYE_STRING_DECODER:
  98. return parser.parseFrom(bytes, extensions);
  99. case BYTE_ARRAY_DECODER:
  100. return parser.parseFrom(bytes.toByteArray(), extensions);
  101. case ARRAY_BYTE_BUFFER_DECODER: {
  102. ByteBuffer buffer = ByteBuffer.allocate(bytes.size());
  103. bytes.copyTo(buffer);
  104. buffer.flip();
  105. try {
  106. return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions);
  107. } catch (InvalidProtocolBufferException e) {
  108. throw e;
  109. }
  110. }
  111. case READONLY_ARRAY_BYTE_BUFFER_DECODER: {
  112. try {
  113. return parser.parseFrom(
  114. CodedInputStream.newInstance(bytes.asReadOnlyByteBuffer()), extensions);
  115. } catch (InvalidProtocolBufferException e) {
  116. throw e;
  117. }
  118. }
  119. case DIRECT_BYTE_BUFFER_DECODER: {
  120. ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size());
  121. bytes.copyTo(buffer);
  122. buffer.flip();
  123. try {
  124. return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions);
  125. } catch (InvalidProtocolBufferException e) {
  126. throw e;
  127. }
  128. }
  129. case READONLY_DIRECT_BYTE_BUFFER_DECODER: {
  130. ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size());
  131. bytes.copyTo(buffer);
  132. buffer.flip();
  133. try {
  134. return parser.parseFrom(
  135. CodedInputStream.newInstance(buffer.asReadOnlyBuffer()), extensions);
  136. } catch (InvalidProtocolBufferException e) {
  137. throw e;
  138. }
  139. }
  140. case INPUT_STREAM_DECODER: {
  141. try {
  142. return parser.parseFrom(bytes.newInput(), extensions);
  143. } catch (InvalidProtocolBufferException e) {
  144. throw e;
  145. }
  146. }
  147. default :
  148. return null;
  149. }
  150. }
  151. }
  152. private <MessageType extends AbstractMessage> MessageType parseBinary(
  153. ByteString bytes, Parser <MessageType> parser, ExtensionRegistry extensions)
  154. throws InvalidProtocolBufferException {
  155. ArrayList <MessageType> messages = new ArrayList <MessageType> ();
  156. ArrayList <InvalidProtocolBufferException> exceptions =
  157. new ArrayList <InvalidProtocolBufferException>();
  158. for (int i = 0; i < BinaryDecoderType.values().length; i++) {
  159. messages.add(null);
  160. exceptions.add(null);
  161. }
  162. BinaryDecoder <MessageType> decoder = new BinaryDecoder <MessageType> ();
  163. boolean hasMessage = false;
  164. boolean hasException = false;
  165. for (int i = 0; i < BinaryDecoderType.values().length; ++i) {
  166. try {
  167. //= BinaryDecoderType.values()[i].parseProto3(bytes);
  168. messages.set(i, decoder.decode(bytes, BinaryDecoderType.values()[i], parser, extensions));
  169. hasMessage = true;
  170. } catch (InvalidProtocolBufferException e) {
  171. exceptions.set(i, e);
  172. hasException = true;
  173. }
  174. }
  175. if (hasMessage && hasException) {
  176. StringBuilder sb =
  177. new StringBuilder("Binary decoders disagreed on whether the payload was valid.\n");
  178. for (int i = 0; i < BinaryDecoderType.values().length; ++i) {
  179. sb.append(BinaryDecoderType.values()[i].name());
  180. if (messages.get(i) != null) {
  181. sb.append(" accepted the payload.\n");
  182. } else {
  183. sb.append(" rejected the payload.\n");
  184. }
  185. }
  186. throw new RuntimeException(sb.toString());
  187. }
  188. if (hasException) {
  189. // We do not check if exceptions are equal. Different implementations may return different
  190. // exception messages. Throw an arbitrary one out instead.
  191. throw exceptions.get(0);
  192. }
  193. // Fast path comparing all the messages with the first message, assuming equality being
  194. // symmetric and transitive.
  195. boolean allEqual = true;
  196. for (int i = 1; i < messages.size(); ++i) {
  197. if (!messages.get(0).equals(messages.get(i))) {
  198. allEqual = false;
  199. break;
  200. }
  201. }
  202. // Slow path: compare and find out all unequal pairs.
  203. if (!allEqual) {
  204. StringBuilder sb = new StringBuilder();
  205. for (int i = 0; i < messages.size() - 1; ++i) {
  206. for (int j = i + 1; j < messages.size(); ++j) {
  207. if (!messages.get(i).equals(messages.get(j))) {
  208. sb.append(BinaryDecoderType.values()[i].name())
  209. .append(" and ")
  210. .append(BinaryDecoderType.values()[j].name())
  211. .append(" parsed the payload differently.\n");
  212. }
  213. }
  214. }
  215. throw new RuntimeException(sb.toString());
  216. }
  217. return messages.get(0);
  218. }
  219. private Conformance.ConformanceResponse doTest(Conformance.ConformanceRequest request) {
  220. com.google.protobuf.AbstractMessage testMessage;
  221. boolean isProto3 =
  222. request.getMessageType().equals("protobuf_test_messages.proto3.TestAllTypesProto3");
  223. boolean isProto2 =
  224. request.getMessageType().equals("protobuf_test_messages.proto2.TestAllTypesProto2");
  225. switch (request.getPayloadCase()) {
  226. case PROTOBUF_PAYLOAD: {
  227. if (isProto3) {
  228. try {
  229. ExtensionRegistry extensions = ExtensionRegistry.newInstance();
  230. TestMessagesProto3.registerAllExtensions(extensions);
  231. testMessage = parseBinary(request.getProtobufPayload(), TestAllTypesProto3.parser(), extensions);
  232. } catch (InvalidProtocolBufferException e) {
  233. return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build();
  234. }
  235. } else if (isProto2) {
  236. try {
  237. ExtensionRegistry extensions = ExtensionRegistry.newInstance();
  238. TestMessagesProto2.registerAllExtensions(extensions);
  239. testMessage = parseBinary(request.getProtobufPayload(), TestAllTypesProto2.parser(), extensions);
  240. } catch (InvalidProtocolBufferException e) {
  241. return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build();
  242. }
  243. } else {
  244. throw new RuntimeException("Protobuf request doesn't have specific payload type.");
  245. }
  246. break;
  247. }
  248. case JSON_PAYLOAD: {
  249. try {
  250. JsonFormat.Parser parser = JsonFormat.parser().usingTypeRegistry(typeRegistry);
  251. if (request.getTestCategory()
  252. == Conformance.TestCategory.JSON_IGNORE_UNKNOWN_PARSING_TEST) {
  253. parser = parser.ignoringUnknownFields();
  254. }
  255. if (isProto3) {
  256. TestMessagesProto3.TestAllTypesProto3.Builder builder =
  257. TestMessagesProto3.TestAllTypesProto3.newBuilder();
  258. parser.merge(request.getJsonPayload(), builder);
  259. testMessage = builder.build();
  260. } else if (isProto2) {
  261. TestMessagesProto2.TestAllTypesProto2.Builder builder =
  262. TestMessagesProto2.TestAllTypesProto2.newBuilder();
  263. parser.merge(request.getJsonPayload(), builder);
  264. testMessage = builder.build();
  265. } else {
  266. throw new RuntimeException("Protobuf request doesn't have specific payload type.");
  267. }
  268. } catch (InvalidProtocolBufferException e) {
  269. return Conformance.ConformanceResponse.newBuilder().setParseError(e.getMessage()).build();
  270. }
  271. break;
  272. }
  273. case TEXT_PAYLOAD: {
  274. if (isProto3) {
  275. try {
  276. TestMessagesProto3.TestAllTypesProto3.Builder builder =
  277. TestMessagesProto3.TestAllTypesProto3.newBuilder();
  278. TextFormat.merge(request.getTextPayload(), builder);
  279. testMessage = builder.build();
  280. } catch (TextFormat.ParseException e) {
  281. return Conformance.ConformanceResponse.newBuilder()
  282. .setParseError(e.getMessage())
  283. .build();
  284. }
  285. } else if (isProto2) {
  286. try {
  287. TestMessagesProto2.TestAllTypesProto2.Builder builder =
  288. TestMessagesProto2.TestAllTypesProto2.newBuilder();
  289. TextFormat.merge(request.getTextPayload(), builder);
  290. testMessage = builder.build();
  291. } catch (TextFormat.ParseException e) {
  292. return Conformance.ConformanceResponse.newBuilder()
  293. .setParseError(e.getMessage())
  294. .build();
  295. }
  296. } else {
  297. throw new RuntimeException("Protobuf request doesn't have specific payload type.");
  298. }
  299. break;
  300. }
  301. case PAYLOAD_NOT_SET: {
  302. throw new RuntimeException("Request didn't have payload.");
  303. }
  304. default: {
  305. throw new RuntimeException("Unexpected payload case.");
  306. }
  307. }
  308. switch (request.getRequestedOutputFormat()) {
  309. case UNSPECIFIED:
  310. throw new RuntimeException("Unspecified output format.");
  311. case PROTOBUF: {
  312. ByteString MessageString = testMessage.toByteString();
  313. return Conformance.ConformanceResponse.newBuilder().setProtobufPayload(MessageString).build();
  314. }
  315. case JSON:
  316. try {
  317. return Conformance.ConformanceResponse.newBuilder().setJsonPayload(
  318. JsonFormat.printer().usingTypeRegistry(typeRegistry).print(testMessage)).build();
  319. } catch (InvalidProtocolBufferException | IllegalArgumentException e) {
  320. return Conformance.ConformanceResponse.newBuilder().setSerializeError(
  321. e.getMessage()).build();
  322. }
  323. case TEXT_FORMAT:
  324. return Conformance.ConformanceResponse.newBuilder().setTextPayload(
  325. TextFormat.printToString(testMessage)).build();
  326. default: {
  327. throw new RuntimeException("Unexpected request output.");
  328. }
  329. }
  330. }
  331. private boolean doTestIo() throws Exception {
  332. int bytes = readLittleEndianIntFromStdin();
  333. if (bytes == -1) {
  334. return false; // EOF
  335. }
  336. byte[] serializedInput = new byte[bytes];
  337. if (!readFromStdin(serializedInput, bytes)) {
  338. throw new RuntimeException("Unexpected EOF from test program.");
  339. }
  340. Conformance.ConformanceRequest request =
  341. Conformance.ConformanceRequest.parseFrom(serializedInput);
  342. Conformance.ConformanceResponse response = doTest(request);
  343. byte[] serializedOutput = response.toByteArray();
  344. writeLittleEndianIntToStdout(serializedOutput.length);
  345. writeToStdout(serializedOutput);
  346. return true;
  347. }
  348. public void run() throws Exception {
  349. typeRegistry = TypeRegistry.newBuilder().add(
  350. TestMessagesProto3.TestAllTypesProto3.getDescriptor()).build();
  351. while (doTestIo()) {
  352. this.testCount++;
  353. }
  354. System.err.println("ConformanceJava: received EOF from test runner after " +
  355. this.testCount + " tests");
  356. }
  357. public static void main(String[] args) throws Exception {
  358. new ConformanceJava().run();
  359. }
  360. }