@SuppressWarnings("unchecked")
    @Override
    public void write(Gson gson, Type type, Object object, OutputStream stream) throws IOException {
      @Nullable JsonWriter writer = null;
      boolean wasOriginalException = false;
      try {
        writer = new JsonWriter(new BufferedWriter(new OutputStreamWriter(stream, CHARSET_NAME)));
        options.setWriterOptions(writer);

        gson.getAdapter((TypeToken<Object>) TypeToken.get(type)).write(writer, object);
      } catch (IOException ex) {
        wasOriginalException = true;
        throw ex;
      } catch (Exception ex) {
        wasOriginalException = true;
        throw new IOException(ex);
      } finally {
        if (writer != null) {
          try {
            // underlying stream should not be closed, just flushing
            writer.flush();
          } catch (IOException ex) {
            if (!wasOriginalException) {
              throw ex;
            }
          }
        }
      }
    }
Creates new provider with flexible setup.
@param options options for provider
gson/src/org/immutables/gson/stream/GsonMessageBodyProvider.java