-
Notifications
You must be signed in to change notification settings - Fork 12
/
MultipartUploadProgress.java
213 lines (187 loc) · 7.87 KB
/
MultipartUploadProgress.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/*
* Copyright (c) 2019, 2020 Moataz Abdelnasser
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.mizosoft.methanol.samples.progress;
import com.github.mizosoft.methanol.Methanol;
import com.github.mizosoft.methanol.MoreBodyHandlers;
import com.github.mizosoft.methanol.MultipartBodyPublisher;
import com.github.mizosoft.methanol.MutableRequest;
import com.github.mizosoft.methanol.ProgressTracker;
import com.github.mizosoft.methanol.ProgressTracker.MultipartProgress;
import java.io.FileNotFoundException;
import java.io.UncheckedIOException;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodySubscribers;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class MultipartUploadProgress extends Application {
private static final int WIDTH = 420;
private static final int HEIGHT = 120;
private static final String URL = "https://httpbin.org/post";
private final Methanol client = Methanol.create();
private final ProgressTracker tracker =
ProgressTracker.newBuilder()
.bytesTransferredThreshold(10 * 1024) // get an event every 10KB at least
.executor(Platform::runLater) // execute listener on JavaFX Application Thread
.build();
private final FileChooser fileChooser = new FileChooser();
private final List<Path> addedFiles = new ArrayList<>();
private final ProgressBar mainProgressBar = new ProgressBar(0.d);
private final ProgressBar perFileProgressBar = new ProgressBar(0.d);
private final Label fileNameLabel = new Label("N/A");
private final Button addFileButton = new Button("Add File");
private final Button resetButton = new Button("Reset");
private final Button uploadButton = new Button("Upload");
private final List<Button> allButtons = List.of(addFileButton, resetButton, uploadButton);
@Override
public void start(Stage primaryStage) {
var progressBarsGridPane = new GridPane();
progressBarsGridPane.setHgap(10.d);
progressBarsGridPane.setVgap(10.d);
var notGrowable = new ColumnConstraints();
notGrowable.setHgrow(Priority.NEVER);
var growable = new ColumnConstraints();
growable.setHgrow(Priority.ALWAYS);
progressBarsGridPane.getColumnConstraints().addAll(notGrowable, growable);
progressBarsGridPane.add(mainProgressBar, 0, 0, 2, 1);
progressBarsGridPane.add(fileNameLabel, 0, 1);
progressBarsGridPane.add(perFileProgressBar, 1, 1);
fileNameLabel.setMaxWidth(100);
mainProgressBar.setMaxWidth(Double.MAX_VALUE);
perFileProgressBar.setMaxWidth(Double.MAX_VALUE);
var buttonBox = new HBox(10.d);
buttonBox.setPadding(new Insets(0.d, 18.d, 0.d, 18.d));
buttonBox.setAlignment(Pos.CENTER);
for (var button : allButtons) {
HBox.setHgrow(button, Priority.ALWAYS);
button.setMaxWidth(Double.MAX_VALUE);
buttonBox.getChildren().add(button);
}
var gridPane = new GridPane();
gridPane.setVgap(10.d);
gridPane.setPadding(new Insets(18.d));
gridPane.add(progressBarsGridPane, 0, 0);
gridPane.add(buttonBox, 0, 1);
gridPane.getColumnConstraints().add(growable);
fileChooser.setTitle("Add File");
setAddFileListener(primaryStage);
setResetListener();
setUploadListener();
primaryStage.setTitle("Multipart Upload Progress");
primaryStage.setScene(new Scene(gridPane, WIDTH, HEIGHT));
primaryStage.show();
}
private void setAddFileListener(Stage primaryStage) {
addFileButton.setOnAction(e -> {
var file = fileChooser.showOpenDialog(primaryStage);
if (file != null) {
addedFiles.add(file.toPath());
}
});
}
private void setResetListener() {
resetButton.setOnAction(e -> addedFiles.clear());
}
private void setUploadListener() {
uploadButton.setOnAction(e -> {
mainProgressBar.setProgress(0.d);
perFileProgressBar.setProgress(0.d);
allButtons.forEach(b -> b.setDisable(true));
uploadFilesAsync()
.whenComplete(
(r, t) -> Platform.runLater(() -> {
perFileProgressBar.setProgress(0.d);
mainProgressBar.setProgress(0.d);
allButtons.forEach(b -> b.setDisable(false));
fileNameLabel.setText("N/A");
}));
});
}
private CompletableFuture<Void> uploadFilesAsync() {
var snapshot =
addedFiles.stream().filter(Files::exists).collect(Collectors.toUnmodifiableList());
if (snapshot.isEmpty()) {
return CompletableFuture.completedFuture(null);
}
var builder = MultipartBodyPublisher.newBuilder();
try {
for (int i = 0; i < snapshot.size(); i++) {
builder.filePart("file_" + i, snapshot.get(i));
}
} catch (FileNotFoundException e) {
throw new UncheckedIOException(e);
}
var request = MutableRequest.POST(
URL, tracker.trackingMultipart(builder.build(), this::onUploadProgress));
return client.sendAsync(request, MoreBodyHandlers.fromAsyncSubscriber(
BodySubscribers.discarding(), __ -> CompletableFuture.<Void>completedFuture(null))) // ignore body completion
.thenApply(HttpResponse::body);
}
private void onUploadProgress(MultipartProgress progress) {
if (progress.partChanged()) {
// Currently file name has to be parsed from headers
// Maybe a ContentDisposition class can be added in future to make this easier
var filename = progress.part()
.headers()
.firstValue("Content-Disposition")
.flatMap(MultipartUploadProgress::getFilenameFromDisposition)
.orElse("UNKNOWN");
fileNameLabel.setText(filename);
}
mainProgressBar.setProgress(progress.value());
perFileProgressBar.setProgress(progress.partProgress().value());
}
private static Optional<String> getFilenameFromDisposition(String disposition) {
int i = disposition.indexOf("filename=");
if (i == -1) {
return Optional.empty();
}
int j = disposition.indexOf(';', i);
int n = i + 9;
var filename = j == -1 ? disposition.substring(n) : disposition.substring(n, j);
if (filename.length() > 2 && filename.startsWith("\"") && filename.endsWith("\"")) {
filename = filename.substring(1, filename.length() - 1);
}
return Optional.of(filename);
}
public static void main(String[] args) {
launch(args);
}
}