Hi,
I think, there is a serious problem with JSONP API, namely JsonWriter is
missing flush() method.
If you want to write JSON message from within the Servlet you will arrive
to such point eventually:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
JsonBuilderFactory bf = Json.createBuilderFactory(null);
JsonObject obj = bf.createObjectBuilder().add("name", "value")
.add("obj", bf.createObjectBuilder()
.add("array",
bf.createArrayBuilder().add("value").add("value2").add("value3")))
.add("obj2", bf.createObjectBuilder().add("amount",
"100.3")).build();
JsonWriter writer = Json.createWriter(resp.getWriter());
writer.write(obj);
}
The problem is that no message will be written to the output writer. It
will be cached in the BufferedWriter's buffer and never flushed (well,
depends on the buffer size, but in this particular example, no single byte
will be flushed to the output).
The only way to flush the writer is to call writer.close() method. But it's
not such a good idea because, as you recall, you should not close output
stream inside the Servlet. Why? One of the reasons might be that the
request is chained and some other servlets or filters might want to add
something to the output stream later (what if you would like to write 10
different JSON messages to the same servlet output?). JSONP breaks this
"contract".
The solution for this would be to add flush() method to JsonWriter
interface or to flush automatically the generator after write() is finished
(then no modification to existing interfaces will be necessary).
Please let me know what you think about this.
Cheers,
Przemyslaw Bielicki