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

     1  {{>licenseInfo}}
     2  
     3  package {{invokerPackage}};
     4  
     5  import okhttp3.MediaType;
     6  import okhttp3.ResponseBody;
     7  
     8  import java.io.IOException;
     9  
    10  import okio.Buffer;
    11  import okio.BufferedSource;
    12  import okio.ForwardingSource;
    13  import okio.Okio;
    14  import okio.Source;
    15  
    16  public class ProgressResponseBody extends ResponseBody {
    17  
    18      private final ResponseBody responseBody;
    19      private final ApiCallback callback;
    20      private BufferedSource bufferedSource;
    21  
    22      public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) {
    23          this.responseBody = responseBody;
    24          this.callback = callback;
    25      }
    26  
    27      @Override
    28      public MediaType contentType() {
    29          return responseBody.contentType();
    30      }
    31  
    32      @Override
    33      public long contentLength() {
    34          return responseBody.contentLength();
    35      }
    36  
    37      @Override
    38      public BufferedSource source() {
    39          if (bufferedSource == null) {
    40              bufferedSource = Okio.buffer(source(responseBody.source()));
    41          }
    42          return bufferedSource;
    43      }
    44  
    45      private Source source(Source source) {
    46          return new ForwardingSource(source) {
    47              long totalBytesRead = 0L;
    48  
    49              @Override
    50              public long read(Buffer sink, long byteCount) throws IOException {
    51                  long bytesRead = super.read(sink, byteCount);
    52                  // read() returns the number of bytes read, or -1 if this source is exhausted.
    53                  totalBytesRead += bytesRead != -1 ? bytesRead : 0;
    54                  callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
    55                  return bytesRead;
    56              }
    57          };
    58      }
    59  }
    60  
    61