/** * Writes and flushes a value to the given {@link OutputStream} * and prevents Jackson from closing it. Also writes newline. * * @param output the {@link OutputStream} * @param value the value to write * @throws IOException on error */ private void writeAndFlushValue(OutputStream output, ObjectNode value) throws IOException { logger.debug("Response: {}", value); for (JsonRpcInterceptor interceptor : interceptorList) { interceptor.postHandleJson(value); } mapper.writeValue(new NoCloseOutputStream(output), value); output.write('\n'); }
@Test public void interceptorsPostHandleJsonExceptionTest() throws IOException { final String requestGood = "{\n" + " \"id\": 0,\n" + " \"jsonrpc\": \"2.0\",\n" + " \"method\": \"testMethod\",\n" + " \"params\": [\"test.cool\"]\n" + " }\n" + "}"; String exceptionMessage = "123"; String returnString = "test"; String responseError = "{\"jsonrpc\":\"2.0\",\"id\":0,\"error\":{\"code\":-32001,\"message\":\"" + exceptionMessage + "\",\"data\":{\"exceptionTypeName\":\"java.lang.RuntimeException\",\"message\":\"" + exceptionMessage + "\"}}}"; // expect(mockService.testMethod(mapper.readTree(requestGood).at("/params/0").asText())).andReturn(returnString); mockInterceptor.postHandleJson(anyObject(JsonNode.class)); expectLastCall().andThrow(new RuntimeException(exceptionMessage)); replay(mockService, mockInterceptor); jsonRpcServer.handleRequest(new ByteArrayInputStream(requestGood.getBytes(StandardCharsets.UTF_8)), byteArrayOutputStream); assertEquals(responseError, byteArrayOutputStream.toString("UTF-8").trim()); verify(mockService, mockInterceptor); }
@Test public void interceptorsNotJsonRpcTest() throws IOException { String requestNotRpc = "{\"test\": 1}"; String responseError = "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"error\":{\"code\":-32601,\"message\":\"method not found\"}}"; //bad call mockInterceptor.preHandleJson(mapper.readTree(requestNotRpc)); expectLastCall().times(1); mockInterceptor.postHandleJson(anyObject(JsonNode.class)); // mockInterceptor.postHandleJson(Util.mapper.readTree(responseError)); this place cause problem // json nodes are same but EasyMock don't understand it expectLastCall().times(1); replay(mockInterceptor); jsonRpcServer.handleRequest(new ByteArrayInputStream(requestNotRpc.getBytes(StandardCharsets.UTF_8)), byteArrayOutputStream); verify(mockInterceptor); }
); expectLastCall().times(1); mockInterceptor.postHandleJson(mapper.readTree(responseGood)); expectLastCall().times(1);