0

I have a rest API that writes the InputStream of the body of a post directly to the database using a PreparedStatement like so:

    public void store(String id, InputStream body) throws SQLException, SPSException {

    if(id == null || id.length() == 0)
        throw new SPSException("get: id is missing: " + id);

    Connection conn = null;
    PreparedStatement ps = null;

    try {
        conn = getConnection();
        Parameters parameters = Parameters.parse("insert into properties (id, body) values (?,?)");

        ps = conn.prepareStatement( parameters.getSQL() );
        ps.setString(1, id );
        ps.setBlob(2, body);
        ps.executeUpdate();

        conn.commit();

    } finally {
        close( ps );
        close( conn );
    }
}

The setBlob call takes the InputStream. Is there a way I can wrap this inputStream with a jsonParser InputStream? So that if the json doesn't parse, an exception is thrown?

I don't want to have to write my own or have to rebuild the stream if I don't have to, but I can't find anything available that would do this with the need for a lot of extra code.

Note - I cannot read the object into memory in its entirety. It has to be a streaming solution.

Mike
  • 609
  • 12
  • 36
  • It's not really a dup, but there are some suggestions for streaming JSON parsers in the answers to [this question](https://stackoverflow.com/questions/9390368/java-best-approach-to-parse-huge-extra-large-json-file) you might want to look at. – azurefrog Jul 11 '19 at 17:29
  • If you want to split, or "tee", input stream, you might want to look at [this question](https://stackoverflow.com/questions/6043634/is-there-a-simple-tee-filter-for-java-streams) – Toris Jul 11 '19 at 18:11
  • But... your question seems to be a SQL/DB related one, so streaming (or store it partially into memory) seems difficult, I think. Rebuild the stream (or just use them as params) with [JsonParser](https://docs.oracle.com/javaee/7/api/javax/json/stream/JsonParser.html) / JsonParser.Event maybe easier to achieve that. – Toris Jul 11 '19 at 18:22

0 Answers0