github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/java/libraries/okhttp-gson/ProgressRequestBody.mustache (about)

     1  {{>licenseInfo}}
     2  
     3  package {{invokerPackage}};
     4  
     5  import okhttp3.MediaType;
     6  import okhttp3.RequestBody;
     7  
     8  import java.io.IOException;
     9  
    10  import okio.Buffer;
    11  import okio.BufferedSink;
    12  import okio.ForwardingSink;
    13  import okio.Okio;
    14  import okio.Sink;
    15  
    16  public class ProgressRequestBody extends RequestBody {
    17  
    18      private final RequestBody requestBody;
    19  
    20      private final ApiCallback callback;
    21  
    22      public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) {
    23          this.requestBody = requestBody;
    24          this.callback = callback;
    25      }
    26  
    27      @Override
    28      public MediaType contentType() {
    29          return requestBody.contentType();
    30      }
    31  
    32      @Override
    33      public long contentLength() throws IOException {
    34          return requestBody.contentLength();
    35      }
    36  
    37      @Override
    38      public void writeTo(BufferedSink sink) throws IOException {
    39          BufferedSink bufferedSink = Okio.buffer(sink(sink));
    40          requestBody.writeTo(bufferedSink);
    41          bufferedSink.flush();
    42      }
    43  
    44      private Sink sink(Sink sink) {
    45          return new ForwardingSink(sink) {
    46  
    47              long bytesWritten = 0L;
    48              long contentLength = 0L;
    49  
    50              @Override
    51              public void write(Buffer source, long byteCount) throws IOException {
    52                  super.write(source, byteCount);
    53                  if (contentLength == 0) {
    54                      contentLength = contentLength();
    55                  }
    56  
    57                  bytesWritten += byteCount;
    58                  callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength);
    59              }
    60          };
    61      }
    62  }