2 * Copyright (C) The Arvados Authors. All rights reserved.
4 * SPDX-License-Identifier: AGPL-3.0 OR Apache-2.0
8 package org.arvados.client.api.client;
10 import okhttp3.MediaType;
11 import okhttp3.RequestBody;
12 import okio.BufferedSink;
15 import org.slf4j.Logger;
21 * {@link} https://gist.github.com/eduardb/dd2dc530afd37108e1ac
23 public class CountingFileRequestBody extends RequestBody {
25 private static final int SEGMENT_SIZE = 2048; // okio.Segment.SIZE
26 private static final MediaType CONTENT_BINARY = MediaType.parse(com.google.common.net.MediaType.OCTET_STREAM.toString());
28 private final File file;
29 private final ProgressListener listener;
31 CountingFileRequestBody(final File file, final ProgressListener listener) {
33 this.listener = listener;
37 public long contentLength() {
42 public MediaType contentType() {
43 return CONTENT_BINARY;
47 public void writeTo(BufferedSink sink) {
48 try (Source source = Okio.source(file)) {
52 while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
55 listener.updateProgress(total);
58 } catch (RuntimeException rethrown) {
60 } catch (Exception ignored) {
65 static class TransferData {
67 private final Logger log = org.slf4j.LoggerFactory.getLogger(TransferData.class);
68 private int progressValue;
69 private long totalSize;
71 TransferData(long totalSize) {
72 this.progressValue = 0;
73 this.totalSize = totalSize;
76 void updateTransferProgress(long transferred) {
77 float progress = (transferred / (float) totalSize) * 100;
78 if (progressValue != (int) progress) {
79 progressValue = (int) progress;
80 log.debug("{} / {} / {}%", transferred, totalSize, progressValue);