I have seen many examples on how to use StreamingOutput
. In my case I want to use it to stream the ResultSet from a database query.
ResultSet rs = (ResultSet) obj;
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
ResultSetFormatter.outputAsJSON(os, rs);
res.close();
}
};
return Response.ok(stream).build();
In this sense write
method definition includes a throws IOException, WebApplicationException
. There is where my problem arise. I need to properly close the connection to the database, resultset, etc. And if an exception is thrown while executing the streaming I don't know how to capture it.
I have tried the following but it's not a valid code as IOException is not thrown from the try-catch block.
try {
.... launch request to database ...
ResultSet rs = (ResultSet) obj;
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
if (accept.equals("application/json") {
ResultSetFormatter.outputAsJSON(os, rs);
} else {
ResultSetFormatter.outputAsXML(os, rs);
}
res.close();
}
};
return Response.ok(stream).build();
} catch (IOException | WebApplicationException e) {
// Do cleanup
}
How can I proceed? Is it possible to properly cleanup everything? I have think even on include all the data processing within the write
method, but the problem is that then I cannot set the Content-type of the response if it is not fixed.
TIA
Edit 1: I'm using SPARQL sentences based on Jena and not SQL database. Depending on the type of query I get different type of responses (Model, Resultset or boolean). Then each one have different valid content types, so I cannot set the content type of the response until the query has been executed or analysed.