IoUtil { public static void streamResponseAndClose(Writer pWriter, JSONStreamAware pJson, String callback) throws IOException { try { if (callback == null) { pJson.writeJSONString(pWriter); } else { pWriter.write(callback); pWriter.write("("); pJson.writeJSONString(pWriter); pWriter.write(");"); } pWriter.write(STREAM_END_MARKER); } finally { pWriter.flush(); pWriter.close(); } } private  IoUtil(); static void streamResponseAndClose(Writer pWriter, JSONStreamAware pJson, String callback);  }
@Test public void checkSmallWrite() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); JSONObject resp = new JSONObject(); resp.put("value", "hello"); String respString = resp.toJSONString(); IoUtil.streamResponseAndClose(writer,resp,null); assertEquals(out.size(), respString.length()); assertEquals(out.toString("UTF-8"), respString); assertWriterClosed(writer); }
@Test public void checkBigWrite() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); JSONArray resp = new JSONArray(); for (int i = 0; i < 10000; i++) { JSONObject data = new JSONObject(); data.put("value", "hello"); resp.add(data); } String respString = resp.toJSONString(); IoUtil.streamResponseAndClose(writer,resp,null); assertEquals(out.size(), respString.length()); assertEquals(out.toString("UTF-8"), respString); assertWriterClosed(writer); }
@Test public void checkWriteWithCallback() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); JSONObject resp = new JSONObject(); resp.put("value", "hello"); String respString = "callbackFunc(" + resp.toJSONString() + ");"; IoUtil.streamResponseAndClose(writer,resp,"callbackFunc"); assertEquals(out.size(), respString.length()); assertEquals(out.toString("UTF-8"), respString); assertWriterClosed(writer); }