• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

box / box-java-sdk / #5076

07 Oct 2025 12:35PM UTC coverage: 37.132% (+0.007%) from 37.125%
#5076

push

github

web-flow
test: Change `Event.additionalDetails` field assertion in events test (box/box-codegen#858) (#1491)

18454 of 49699 relevant lines covered (37.13%)

0.37 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.29
/src/main/java/com/box/sdkgen/managers/chunkeduploads/ChunkedUploadsManager.java
1
package com.box.sdkgen.managers.chunkeduploads;
2

3
import static com.box.sdkgen.internal.utils.UtilsManager.bufferLength;
4
import static com.box.sdkgen.internal.utils.UtilsManager.convertToString;
5
import static com.box.sdkgen.internal.utils.UtilsManager.entryOf;
6
import static com.box.sdkgen.internal.utils.UtilsManager.generateByteStreamFromBuffer;
7
import static com.box.sdkgen.internal.utils.UtilsManager.hexToBase64;
8
import static com.box.sdkgen.internal.utils.UtilsManager.iterateChunks;
9
import static com.box.sdkgen.internal.utils.UtilsManager.mapOf;
10
import static com.box.sdkgen.internal.utils.UtilsManager.mergeMaps;
11
import static com.box.sdkgen.internal.utils.UtilsManager.prepareParams;
12
import static com.box.sdkgen.internal.utils.UtilsManager.readByteStream;
13
import static com.box.sdkgen.internal.utils.UtilsManager.reduceIterator;
14

15
import com.box.sdkgen.internal.utils.Hash;
16
import com.box.sdkgen.internal.utils.HashName;
17
import com.box.sdkgen.networking.auth.Authentication;
18
import com.box.sdkgen.networking.fetchoptions.FetchOptions;
19
import com.box.sdkgen.networking.fetchoptions.ResponseFormat;
20
import com.box.sdkgen.networking.fetchresponse.FetchResponse;
21
import com.box.sdkgen.networking.network.NetworkSession;
22
import com.box.sdkgen.schemas.filefull.FileFull;
23
import com.box.sdkgen.schemas.files.Files;
24
import com.box.sdkgen.schemas.uploadedpart.UploadedPart;
25
import com.box.sdkgen.schemas.uploadpart.UploadPart;
26
import com.box.sdkgen.schemas.uploadparts.UploadParts;
27
import com.box.sdkgen.schemas.uploadsession.UploadSession;
28
import com.box.sdkgen.serialization.json.JsonManager;
29
import java.io.InputStream;
30
import java.util.Arrays;
31
import java.util.Collections;
32
import java.util.Iterator;
33
import java.util.List;
34
import java.util.Map;
35
import java.util.stream.Collectors;
36
import java.util.stream.Stream;
37

38
public class ChunkedUploadsManager {
1✔
39

40
  public Authentication auth;
41

42
  public NetworkSession networkSession;
43

44
  public ChunkedUploadsManager() {
×
45
    this.networkSession = new NetworkSession();
×
46
  }
×
47

48
  protected ChunkedUploadsManager(Builder builder) {
1✔
49
    this.auth = builder.auth;
1✔
50
    this.networkSession = builder.networkSession;
1✔
51
  }
1✔
52

53
  /**
54
   * Creates an upload session for a new file.
55
   *
56
   * @param requestBody Request body of createFileUploadSession method
57
   */
58
  public UploadSession createFileUploadSession(CreateFileUploadSessionRequestBody requestBody) {
59
    return createFileUploadSession(requestBody, new CreateFileUploadSessionHeaders());
1✔
60
  }
61

62
  /**
63
   * Creates an upload session for a new file.
64
   *
65
   * @param requestBody Request body of createFileUploadSession method
66
   * @param headers Headers of createFileUploadSession method
67
   */
68
  public UploadSession createFileUploadSession(
69
      CreateFileUploadSessionRequestBody requestBody, CreateFileUploadSessionHeaders headers) {
70
    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
1✔
71
    FetchResponse response =
1✔
72
        this.networkSession
73
            .getNetworkClient()
1✔
74
            .fetch(
1✔
75
                new FetchOptions.Builder(
76
                        String.join(
1✔
77
                            "",
78
                            this.networkSession.getBaseUrls().getUploadUrl(),
1✔
79
                            "/2.0/files/upload_sessions"),
80
                        "POST")
81
                    .headers(headersMap)
1✔
82
                    .data(JsonManager.serialize(requestBody))
1✔
83
                    .contentType("application/json")
1✔
84
                    .responseFormat(ResponseFormat.JSON)
1✔
85
                    .auth(this.auth)
1✔
86
                    .networkSession(this.networkSession)
1✔
87
                    .build());
1✔
88
    return JsonManager.deserialize(response.getData(), UploadSession.class);
1✔
89
  }
90

91
  /**
92
   * Creates an upload session for an existing file.
93
   *
94
   * @param fileId The unique identifier that represents a file.
95
   *     <p>The ID for any file can be determined by visiting a file in the web application and
96
   *     copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the
97
   *     `file_id` is `123`. Example: "12345"
98
   * @param requestBody Request body of createFileUploadSessionForExistingFile method
99
   */
100
  public UploadSession createFileUploadSessionForExistingFile(
101
      String fileId, CreateFileUploadSessionForExistingFileRequestBody requestBody) {
102
    return createFileUploadSessionForExistingFile(
×
103
        fileId, requestBody, new CreateFileUploadSessionForExistingFileHeaders());
104
  }
105

106
  /**
107
   * Creates an upload session for an existing file.
108
   *
109
   * @param fileId The unique identifier that represents a file.
110
   *     <p>The ID for any file can be determined by visiting a file in the web application and
111
   *     copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the
112
   *     `file_id` is `123`. Example: "12345"
113
   * @param requestBody Request body of createFileUploadSessionForExistingFile method
114
   * @param headers Headers of createFileUploadSessionForExistingFile method
115
   */
116
  public UploadSession createFileUploadSessionForExistingFile(
117
      String fileId,
118
      CreateFileUploadSessionForExistingFileRequestBody requestBody,
119
      CreateFileUploadSessionForExistingFileHeaders headers) {
120
    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
×
121
    FetchResponse response =
×
122
        this.networkSession
123
            .getNetworkClient()
×
124
            .fetch(
×
125
                new FetchOptions.Builder(
126
                        String.join(
×
127
                            "",
128
                            this.networkSession.getBaseUrls().getUploadUrl(),
×
129
                            "/2.0/files/",
130
                            convertToString(fileId),
×
131
                            "/upload_sessions"),
132
                        "POST")
133
                    .headers(headersMap)
×
134
                    .data(JsonManager.serialize(requestBody))
×
135
                    .contentType("application/json")
×
136
                    .responseFormat(ResponseFormat.JSON)
×
137
                    .auth(this.auth)
×
138
                    .networkSession(this.networkSession)
×
139
                    .build());
×
140
    return JsonManager.deserialize(response.getData(), UploadSession.class);
×
141
  }
142

143
  /**
144
   * Using this method with urls provided in response when creating a new upload session is
145
   * preferred to use over GetFileUploadSessionById method. This allows to always upload your
146
   * content to the closest Box data center and can significantly improve upload speed. Return
147
   * information about an upload session.
148
   *
149
   * <p>The actual endpoint URL is returned by the [`Create upload
150
   * session`](e://post-files-upload-sessions) endpoint.
151
   *
152
   * @param url URL of getFileUploadSessionById method
153
   */
154
  public UploadSession getFileUploadSessionByUrl(String url) {
155
    return getFileUploadSessionByUrl(url, new GetFileUploadSessionByUrlHeaders());
1✔
156
  }
157

158
  /**
159
   * Using this method with urls provided in response when creating a new upload session is
160
   * preferred to use over GetFileUploadSessionById method. This allows to always upload your
161
   * content to the closest Box data center and can significantly improve upload speed. Return
162
   * information about an upload session.
163
   *
164
   * <p>The actual endpoint URL is returned by the [`Create upload
165
   * session`](e://post-files-upload-sessions) endpoint.
166
   *
167
   * @param url URL of getFileUploadSessionById method
168
   * @param headers Headers of getFileUploadSessionById method
169
   */
170
  public UploadSession getFileUploadSessionByUrl(
171
      String url, GetFileUploadSessionByUrlHeaders headers) {
172
    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
1✔
173
    FetchResponse response =
1✔
174
        this.networkSession
175
            .getNetworkClient()
1✔
176
            .fetch(
1✔
177
                new FetchOptions.Builder(url, "GET")
178
                    .headers(headersMap)
1✔
179
                    .responseFormat(ResponseFormat.JSON)
1✔
180
                    .auth(this.auth)
1✔
181
                    .networkSession(this.networkSession)
1✔
182
                    .build());
1✔
183
    return JsonManager.deserialize(response.getData(), UploadSession.class);
1✔
184
  }
185

186
  /**
187
   * Return information about an upload session.
188
   *
189
   * <p>The actual endpoint URL is returned by the [`Create upload
190
   * session`](e://post-files-upload-sessions) endpoint.
191
   *
192
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
193
   */
194
  public UploadSession getFileUploadSessionById(String uploadSessionId) {
195
    return getFileUploadSessionById(uploadSessionId, new GetFileUploadSessionByIdHeaders());
1✔
196
  }
197

198
  /**
199
   * Return information about an upload session.
200
   *
201
   * <p>The actual endpoint URL is returned by the [`Create upload
202
   * session`](e://post-files-upload-sessions) endpoint.
203
   *
204
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
205
   * @param headers Headers of getFileUploadSessionById method
206
   */
207
  public UploadSession getFileUploadSessionById(
208
      String uploadSessionId, GetFileUploadSessionByIdHeaders headers) {
209
    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
1✔
210
    FetchResponse response =
1✔
211
        this.networkSession
212
            .getNetworkClient()
1✔
213
            .fetch(
1✔
214
                new FetchOptions.Builder(
215
                        String.join(
1✔
216
                            "",
217
                            this.networkSession.getBaseUrls().getUploadUrl(),
1✔
218
                            "/2.0/files/upload_sessions/",
219
                            convertToString(uploadSessionId)),
1✔
220
                        "GET")
221
                    .headers(headersMap)
1✔
222
                    .responseFormat(ResponseFormat.JSON)
1✔
223
                    .auth(this.auth)
1✔
224
                    .networkSession(this.networkSession)
1✔
225
                    .build());
1✔
226
    return JsonManager.deserialize(response.getData(), UploadSession.class);
1✔
227
  }
228

229
  /**
230
   * Using this method with urls provided in response when creating a new upload session is
231
   * preferred to use over UploadFilePart method. This allows to always upload your content to the
232
   * closest Box data center and can significantly improve upload speed. Uploads a chunk of a file
233
   * for an upload session.
234
   *
235
   * <p>The actual endpoint URL is returned by the [`Create upload
236
   * session`](e://post-files-upload-sessions) and [`Get upload
237
   * session`](e://get-files-upload-sessions-id) endpoints.
238
   *
239
   * @param url URL of uploadFilePart method
240
   * @param requestBody Request body of uploadFilePart method
241
   * @param headers Headers of uploadFilePart method
242
   */
243
  public UploadedPart uploadFilePartByUrl(
244
      String url, InputStream requestBody, UploadFilePartByUrlHeaders headers) {
245
    Map<String, String> headersMap =
1✔
246
        prepareParams(
1✔
247
            mergeMaps(
1✔
248
                mapOf(
1✔
249
                    entryOf("digest", convertToString(headers.getDigest())),
1✔
250
                    entryOf("content-range", convertToString(headers.getContentRange()))),
1✔
251
                headers.getExtraHeaders()));
1✔
252
    FetchResponse response =
1✔
253
        this.networkSession
254
            .getNetworkClient()
1✔
255
            .fetch(
1✔
256
                new FetchOptions.Builder(url, "PUT")
257
                    .headers(headersMap)
1✔
258
                    .fileStream(requestBody)
1✔
259
                    .contentType("application/octet-stream")
1✔
260
                    .responseFormat(ResponseFormat.JSON)
1✔
261
                    .auth(this.auth)
1✔
262
                    .networkSession(this.networkSession)
1✔
263
                    .build());
1✔
264
    return JsonManager.deserialize(response.getData(), UploadedPart.class);
1✔
265
  }
266

267
  /**
268
   * Uploads a chunk of a file for an upload session.
269
   *
270
   * <p>The actual endpoint URL is returned by the [`Create upload
271
   * session`](e://post-files-upload-sessions) and [`Get upload
272
   * session`](e://get-files-upload-sessions-id) endpoints.
273
   *
274
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
275
   * @param requestBody Request body of uploadFilePart method
276
   * @param headers Headers of uploadFilePart method
277
   */
278
  public UploadedPart uploadFilePart(
279
      String uploadSessionId, InputStream requestBody, UploadFilePartHeaders headers) {
280
    Map<String, String> headersMap =
1✔
281
        prepareParams(
1✔
282
            mergeMaps(
1✔
283
                mapOf(
1✔
284
                    entryOf("digest", convertToString(headers.getDigest())),
1✔
285
                    entryOf("content-range", convertToString(headers.getContentRange()))),
1✔
286
                headers.getExtraHeaders()));
1✔
287
    FetchResponse response =
1✔
288
        this.networkSession
289
            .getNetworkClient()
1✔
290
            .fetch(
1✔
291
                new FetchOptions.Builder(
292
                        String.join(
1✔
293
                            "",
294
                            this.networkSession.getBaseUrls().getUploadUrl(),
1✔
295
                            "/2.0/files/upload_sessions/",
296
                            convertToString(uploadSessionId)),
1✔
297
                        "PUT")
298
                    .headers(headersMap)
1✔
299
                    .fileStream(requestBody)
1✔
300
                    .contentType("application/octet-stream")
1✔
301
                    .responseFormat(ResponseFormat.JSON)
1✔
302
                    .auth(this.auth)
1✔
303
                    .networkSession(this.networkSession)
1✔
304
                    .build());
1✔
305
    return JsonManager.deserialize(response.getData(), UploadedPart.class);
1✔
306
  }
307

308
  /**
309
   * Using this method with urls provided in response when creating a new upload session is
310
   * preferred to use over DeleteFileUploadSessionById method. This allows to always upload your
311
   * content to the closest Box data center and can significantly improve upload speed. Abort an
312
   * upload session and discard all data uploaded.
313
   *
314
   * <p>This cannot be reversed.
315
   *
316
   * <p>The actual endpoint URL is returned by the [`Create upload
317
   * session`](e://post-files-upload-sessions) and [`Get upload
318
   * session`](e://get-files-upload-sessions-id) endpoints.
319
   *
320
   * @param url URL of deleteFileUploadSessionById method
321
   */
322
  public void deleteFileUploadSessionByUrl(String url) {
323
    deleteFileUploadSessionByUrl(url, new DeleteFileUploadSessionByUrlHeaders());
1✔
324
  }
1✔
325

326
  /**
327
   * Using this method with urls provided in response when creating a new upload session is
328
   * preferred to use over DeleteFileUploadSessionById method. This allows to always upload your
329
   * content to the closest Box data center and can significantly improve upload speed. Abort an
330
   * upload session and discard all data uploaded.
331
   *
332
   * <p>This cannot be reversed.
333
   *
334
   * <p>The actual endpoint URL is returned by the [`Create upload
335
   * session`](e://post-files-upload-sessions) and [`Get upload
336
   * session`](e://get-files-upload-sessions-id) endpoints.
337
   *
338
   * @param url URL of deleteFileUploadSessionById method
339
   * @param headers Headers of deleteFileUploadSessionById method
340
   */
341
  public void deleteFileUploadSessionByUrl(
342
      String url, DeleteFileUploadSessionByUrlHeaders headers) {
343
    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
1✔
344
    FetchResponse response =
1✔
345
        this.networkSession
346
            .getNetworkClient()
1✔
347
            .fetch(
1✔
348
                new FetchOptions.Builder(url, "DELETE")
349
                    .headers(headersMap)
1✔
350
                    .responseFormat(ResponseFormat.NO_CONTENT)
1✔
351
                    .auth(this.auth)
1✔
352
                    .networkSession(this.networkSession)
1✔
353
                    .build());
1✔
354
  }
1✔
355

356
  /**
357
   * Abort an upload session and discard all data uploaded.
358
   *
359
   * <p>This cannot be reversed.
360
   *
361
   * <p>The actual endpoint URL is returned by the [`Create upload
362
   * session`](e://post-files-upload-sessions) and [`Get upload
363
   * session`](e://get-files-upload-sessions-id) endpoints.
364
   *
365
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
366
   */
367
  public void deleteFileUploadSessionById(String uploadSessionId) {
368
    deleteFileUploadSessionById(uploadSessionId, new DeleteFileUploadSessionByIdHeaders());
1✔
369
  }
1✔
370

371
  /**
372
   * Abort an upload session and discard all data uploaded.
373
   *
374
   * <p>This cannot be reversed.
375
   *
376
   * <p>The actual endpoint URL is returned by the [`Create upload
377
   * session`](e://post-files-upload-sessions) and [`Get upload
378
   * session`](e://get-files-upload-sessions-id) endpoints.
379
   *
380
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
381
   * @param headers Headers of deleteFileUploadSessionById method
382
   */
383
  public void deleteFileUploadSessionById(
384
      String uploadSessionId, DeleteFileUploadSessionByIdHeaders headers) {
385
    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
1✔
386
    FetchResponse response =
1✔
387
        this.networkSession
388
            .getNetworkClient()
1✔
389
            .fetch(
1✔
390
                new FetchOptions.Builder(
391
                        String.join(
1✔
392
                            "",
393
                            this.networkSession.getBaseUrls().getUploadUrl(),
1✔
394
                            "/2.0/files/upload_sessions/",
395
                            convertToString(uploadSessionId)),
1✔
396
                        "DELETE")
397
                    .headers(headersMap)
1✔
398
                    .responseFormat(ResponseFormat.NO_CONTENT)
1✔
399
                    .auth(this.auth)
1✔
400
                    .networkSession(this.networkSession)
1✔
401
                    .build());
1✔
402
  }
1✔
403

404
  /**
405
   * Using this method with urls provided in response when creating a new upload session is
406
   * preferred to use over GetFileUploadSessionParts method. This allows to always upload your
407
   * content to the closest Box data center and can significantly improve upload speed. Return a
408
   * list of the chunks uploaded to the upload session so far.
409
   *
410
   * <p>The actual endpoint URL is returned by the [`Create upload
411
   * session`](e://post-files-upload-sessions) and [`Get upload
412
   * session`](e://get-files-upload-sessions-id) endpoints.
413
   *
414
   * @param url URL of getFileUploadSessionParts method
415
   */
416
  public UploadParts getFileUploadSessionPartsByUrl(String url) {
417
    return getFileUploadSessionPartsByUrl(
1✔
418
        url,
419
        new GetFileUploadSessionPartsByUrlQueryParams(),
420
        new GetFileUploadSessionPartsByUrlHeaders());
421
  }
422

423
  /**
424
   * Using this method with urls provided in response when creating a new upload session is
425
   * preferred to use over GetFileUploadSessionParts method. This allows to always upload your
426
   * content to the closest Box data center and can significantly improve upload speed. Return a
427
   * list of the chunks uploaded to the upload session so far.
428
   *
429
   * <p>The actual endpoint URL is returned by the [`Create upload
430
   * session`](e://post-files-upload-sessions) and [`Get upload
431
   * session`](e://get-files-upload-sessions-id) endpoints.
432
   *
433
   * @param url URL of getFileUploadSessionParts method
434
   * @param queryParams Query parameters of getFileUploadSessionParts method
435
   */
436
  public UploadParts getFileUploadSessionPartsByUrl(
437
      String url, GetFileUploadSessionPartsByUrlQueryParams queryParams) {
438
    return getFileUploadSessionPartsByUrl(
×
439
        url, queryParams, new GetFileUploadSessionPartsByUrlHeaders());
440
  }
441

442
  /**
443
   * Using this method with urls provided in response when creating a new upload session is
444
   * preferred to use over GetFileUploadSessionParts method. This allows to always upload your
445
   * content to the closest Box data center and can significantly improve upload speed. Return a
446
   * list of the chunks uploaded to the upload session so far.
447
   *
448
   * <p>The actual endpoint URL is returned by the [`Create upload
449
   * session`](e://post-files-upload-sessions) and [`Get upload
450
   * session`](e://get-files-upload-sessions-id) endpoints.
451
   *
452
   * @param url URL of getFileUploadSessionParts method
453
   * @param headers Headers of getFileUploadSessionParts method
454
   */
455
  public UploadParts getFileUploadSessionPartsByUrl(
456
      String url, GetFileUploadSessionPartsByUrlHeaders headers) {
457
    return getFileUploadSessionPartsByUrl(
×
458
        url, new GetFileUploadSessionPartsByUrlQueryParams(), headers);
459
  }
460

461
  /**
462
   * Using this method with urls provided in response when creating a new upload session is
463
   * preferred to use over GetFileUploadSessionParts method. This allows to always upload your
464
   * content to the closest Box data center and can significantly improve upload speed. Return a
465
   * list of the chunks uploaded to the upload session so far.
466
   *
467
   * <p>The actual endpoint URL is returned by the [`Create upload
468
   * session`](e://post-files-upload-sessions) and [`Get upload
469
   * session`](e://get-files-upload-sessions-id) endpoints.
470
   *
471
   * @param url URL of getFileUploadSessionParts method
472
   * @param queryParams Query parameters of getFileUploadSessionParts method
473
   * @param headers Headers of getFileUploadSessionParts method
474
   */
475
  public UploadParts getFileUploadSessionPartsByUrl(
476
      String url,
477
      GetFileUploadSessionPartsByUrlQueryParams queryParams,
478
      GetFileUploadSessionPartsByUrlHeaders headers) {
479
    Map<String, String> queryParamsMap =
1✔
480
        prepareParams(
1✔
481
            mapOf(
1✔
482
                entryOf("offset", convertToString(queryParams.getOffset())),
1✔
483
                entryOf("limit", convertToString(queryParams.getLimit()))));
1✔
484
    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
1✔
485
    FetchResponse response =
1✔
486
        this.networkSession
487
            .getNetworkClient()
1✔
488
            .fetch(
1✔
489
                new FetchOptions.Builder(url, "GET")
490
                    .params(queryParamsMap)
1✔
491
                    .headers(headersMap)
1✔
492
                    .responseFormat(ResponseFormat.JSON)
1✔
493
                    .auth(this.auth)
1✔
494
                    .networkSession(this.networkSession)
1✔
495
                    .build());
1✔
496
    return JsonManager.deserialize(response.getData(), UploadParts.class);
1✔
497
  }
498

499
  /**
500
   * Return a list of the chunks uploaded to the upload session so far.
501
   *
502
   * <p>The actual endpoint URL is returned by the [`Create upload
503
   * session`](e://post-files-upload-sessions) and [`Get upload
504
   * session`](e://get-files-upload-sessions-id) endpoints.
505
   *
506
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
507
   */
508
  public UploadParts getFileUploadSessionParts(String uploadSessionId) {
509
    return getFileUploadSessionParts(
1✔
510
        uploadSessionId,
511
        new GetFileUploadSessionPartsQueryParams(),
512
        new GetFileUploadSessionPartsHeaders());
513
  }
514

515
  /**
516
   * Return a list of the chunks uploaded to the upload session so far.
517
   *
518
   * <p>The actual endpoint URL is returned by the [`Create upload
519
   * session`](e://post-files-upload-sessions) and [`Get upload
520
   * session`](e://get-files-upload-sessions-id) endpoints.
521
   *
522
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
523
   * @param queryParams Query parameters of getFileUploadSessionParts method
524
   */
525
  public UploadParts getFileUploadSessionParts(
526
      String uploadSessionId, GetFileUploadSessionPartsQueryParams queryParams) {
527
    return getFileUploadSessionParts(
×
528
        uploadSessionId, queryParams, new GetFileUploadSessionPartsHeaders());
529
  }
530

531
  /**
532
   * Return a list of the chunks uploaded to the upload session so far.
533
   *
534
   * <p>The actual endpoint URL is returned by the [`Create upload
535
   * session`](e://post-files-upload-sessions) and [`Get upload
536
   * session`](e://get-files-upload-sessions-id) endpoints.
537
   *
538
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
539
   * @param headers Headers of getFileUploadSessionParts method
540
   */
541
  public UploadParts getFileUploadSessionParts(
542
      String uploadSessionId, GetFileUploadSessionPartsHeaders headers) {
543
    return getFileUploadSessionParts(
×
544
        uploadSessionId, new GetFileUploadSessionPartsQueryParams(), headers);
545
  }
546

547
  /**
548
   * Return a list of the chunks uploaded to the upload session so far.
549
   *
550
   * <p>The actual endpoint URL is returned by the [`Create upload
551
   * session`](e://post-files-upload-sessions) and [`Get upload
552
   * session`](e://get-files-upload-sessions-id) endpoints.
553
   *
554
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
555
   * @param queryParams Query parameters of getFileUploadSessionParts method
556
   * @param headers Headers of getFileUploadSessionParts method
557
   */
558
  public UploadParts getFileUploadSessionParts(
559
      String uploadSessionId,
560
      GetFileUploadSessionPartsQueryParams queryParams,
561
      GetFileUploadSessionPartsHeaders headers) {
562
    Map<String, String> queryParamsMap =
1✔
563
        prepareParams(
1✔
564
            mapOf(
1✔
565
                entryOf("offset", convertToString(queryParams.getOffset())),
1✔
566
                entryOf("limit", convertToString(queryParams.getLimit()))));
1✔
567
    Map<String, String> headersMap = prepareParams(mergeMaps(mapOf(), headers.getExtraHeaders()));
1✔
568
    FetchResponse response =
1✔
569
        this.networkSession
570
            .getNetworkClient()
1✔
571
            .fetch(
1✔
572
                new FetchOptions.Builder(
573
                        String.join(
1✔
574
                            "",
575
                            this.networkSession.getBaseUrls().getUploadUrl(),
1✔
576
                            "/2.0/files/upload_sessions/",
577
                            convertToString(uploadSessionId),
1✔
578
                            "/parts"),
579
                        "GET")
580
                    .params(queryParamsMap)
1✔
581
                    .headers(headersMap)
1✔
582
                    .responseFormat(ResponseFormat.JSON)
1✔
583
                    .auth(this.auth)
1✔
584
                    .networkSession(this.networkSession)
1✔
585
                    .build());
1✔
586
    return JsonManager.deserialize(response.getData(), UploadParts.class);
1✔
587
  }
588

589
  /**
590
   * Using this method with urls provided in response when creating a new upload session is
591
   * preferred to use over CreateFileUploadSessionCommit method. This allows to always upload your
592
   * content to the closest Box data center and can significantly improve upload speed. Close an
593
   * upload session and create a file from the uploaded chunks.
594
   *
595
   * <p>The actual endpoint URL is returned by the [`Create upload
596
   * session`](e://post-files-upload-sessions) and [`Get upload
597
   * session`](e://get-files-upload-sessions-id) endpoints.
598
   *
599
   * @param url URL of createFileUploadSessionCommit method
600
   * @param requestBody Request body of createFileUploadSessionCommit method
601
   * @param headers Headers of createFileUploadSessionCommit method
602
   */
603
  public Files createFileUploadSessionCommitByUrl(
604
      String url,
605
      CreateFileUploadSessionCommitByUrlRequestBody requestBody,
606
      CreateFileUploadSessionCommitByUrlHeaders headers) {
607
    Map<String, String> headersMap =
1✔
608
        prepareParams(
1✔
609
            mergeMaps(
1✔
610
                mapOf(
1✔
611
                    entryOf("digest", convertToString(headers.getDigest())),
1✔
612
                    entryOf("if-match", convertToString(headers.getIfMatch())),
1✔
613
                    entryOf("if-none-match", convertToString(headers.getIfNoneMatch()))),
1✔
614
                headers.getExtraHeaders()));
1✔
615
    FetchResponse response =
1✔
616
        this.networkSession
617
            .getNetworkClient()
1✔
618
            .fetch(
1✔
619
                new FetchOptions.Builder(url, "POST")
620
                    .headers(headersMap)
1✔
621
                    .data(JsonManager.serialize(requestBody))
1✔
622
                    .contentType("application/json")
1✔
623
                    .responseFormat(ResponseFormat.JSON)
1✔
624
                    .auth(this.auth)
1✔
625
                    .networkSession(this.networkSession)
1✔
626
                    .build());
1✔
627
    if (convertToString(response.getStatus()).equals("202")) {
1✔
628
      return null;
×
629
    }
630
    return JsonManager.deserialize(response.getData(), Files.class);
1✔
631
  }
632

633
  /**
634
   * Close an upload session and create a file from the uploaded chunks.
635
   *
636
   * <p>The actual endpoint URL is returned by the [`Create upload
637
   * session`](e://post-files-upload-sessions) and [`Get upload
638
   * session`](e://get-files-upload-sessions-id) endpoints.
639
   *
640
   * @param uploadSessionId The ID of the upload session. Example: "D5E3F7A"
641
   * @param requestBody Request body of createFileUploadSessionCommit method
642
   * @param headers Headers of createFileUploadSessionCommit method
643
   */
644
  public Files createFileUploadSessionCommit(
645
      String uploadSessionId,
646
      CreateFileUploadSessionCommitRequestBody requestBody,
647
      CreateFileUploadSessionCommitHeaders headers) {
648
    Map<String, String> headersMap =
1✔
649
        prepareParams(
1✔
650
            mergeMaps(
1✔
651
                mapOf(
1✔
652
                    entryOf("digest", convertToString(headers.getDigest())),
1✔
653
                    entryOf("if-match", convertToString(headers.getIfMatch())),
1✔
654
                    entryOf("if-none-match", convertToString(headers.getIfNoneMatch()))),
1✔
655
                headers.getExtraHeaders()));
1✔
656
    FetchResponse response =
1✔
657
        this.networkSession
658
            .getNetworkClient()
1✔
659
            .fetch(
1✔
660
                new FetchOptions.Builder(
661
                        String.join(
1✔
662
                            "",
663
                            this.networkSession.getBaseUrls().getUploadUrl(),
1✔
664
                            "/2.0/files/upload_sessions/",
665
                            convertToString(uploadSessionId),
1✔
666
                            "/commit"),
667
                        "POST")
668
                    .headers(headersMap)
1✔
669
                    .data(JsonManager.serialize(requestBody))
1✔
670
                    .contentType("application/json")
1✔
671
                    .responseFormat(ResponseFormat.JSON)
1✔
672
                    .auth(this.auth)
1✔
673
                    .networkSession(this.networkSession)
1✔
674
                    .build());
1✔
675
    if (convertToString(response.getStatus()).equals("202")) {
1✔
676
      return null;
×
677
    }
678
    return JsonManager.deserialize(response.getData(), Files.class);
1✔
679
  }
680

681
  public PartAccumulator reducer(PartAccumulator acc, InputStream chunk) {
682
    long lastIndex = acc.getLastIndex();
1✔
683
    List<UploadPart> parts = acc.getParts();
1✔
684
    byte[] chunkBuffer = readByteStream(chunk);
1✔
685
    Hash hash = new Hash(HashName.SHA1);
1✔
686
    hash.updateHash(chunkBuffer);
1✔
687
    String sha1 = hash.digestHash("base64");
1✔
688
    String digest = String.join("", "sha=", sha1);
1✔
689
    int chunkSize = bufferLength(chunkBuffer);
1✔
690
    long bytesStart = lastIndex + 1;
1✔
691
    long bytesEnd = lastIndex + chunkSize;
1✔
692
    String contentRange =
1✔
693
        String.join(
1✔
694
            "",
695
            "bytes ",
696
            convertToString(bytesStart),
1✔
697
            "-",
698
            convertToString(bytesEnd),
1✔
699
            "/",
700
            convertToString(acc.getFileSize()));
1✔
701
    UploadedPart uploadedPart =
1✔
702
        this.uploadFilePartByUrl(
1✔
703
            acc.getUploadPartUrl(),
1✔
704
            generateByteStreamFromBuffer(chunkBuffer),
1✔
705
            new UploadFilePartByUrlHeaders(digest, contentRange));
706
    UploadPart part = uploadedPart.getPart();
1✔
707
    String partSha1 = hexToBase64(part.getSha1());
1✔
708
    assert partSha1.equals(sha1);
1✔
709
    assert part.getSize() == chunkSize;
1✔
710
    assert part.getOffset() == bytesStart;
1✔
711
    acc.getFileHash().updateHash(chunkBuffer);
1✔
712
    return new PartAccumulator(
1✔
713
        bytesEnd,
714
        Stream.concat(parts.stream(), Arrays.asList(part).stream()).collect(Collectors.toList()),
1✔
715
        acc.getFileSize(),
1✔
716
        acc.getUploadPartUrl(),
1✔
717
        acc.getFileHash());
1✔
718
  }
719

720
  /**
721
   * Starts the process of chunk uploading a big file. Should return a File object representing
722
   * uploaded file.
723
   *
724
   * @param file The stream of the file to upload.
725
   * @param fileName The name of the file, which will be used for storage in Box.
726
   * @param fileSize The total size of the file for the chunked upload in bytes.
727
   * @param parentFolderId The ID of the folder where the file should be uploaded.
728
   */
729
  public FileFull uploadBigFile(
730
      InputStream file, String fileName, long fileSize, String parentFolderId) {
731
    UploadSession uploadSession =
1✔
732
        this.createFileUploadSession(
1✔
733
            new CreateFileUploadSessionRequestBody(parentFolderId, fileSize, fileName));
734
    String uploadPartUrl = uploadSession.getSessionEndpoints().getUploadPart();
1✔
735
    String commitUrl = uploadSession.getSessionEndpoints().getCommit();
1✔
736
    String listPartsUrl = uploadSession.getSessionEndpoints().getListParts();
1✔
737
    long partSize = uploadSession.getPartSize();
1✔
738
    int totalParts = uploadSession.getTotalParts();
1✔
739
    assert partSize * totalParts >= fileSize;
1✔
740
    assert uploadSession.getNumPartsProcessed() == 0;
1✔
741
    Hash fileHash = new Hash(HashName.SHA1);
1✔
742
    Iterator<InputStream> chunksIterator = iterateChunks(file, partSize, fileSize);
1✔
743
    PartAccumulator results =
1✔
744
        reduceIterator(
1✔
745
            chunksIterator,
746
            this::reducer,
747
            new PartAccumulator(-1, Collections.emptyList(), fileSize, uploadPartUrl, fileHash));
1✔
748
    List<UploadPart> parts = results.getParts();
1✔
749
    UploadParts processedSessionParts = this.getFileUploadSessionPartsByUrl(listPartsUrl);
1✔
750
    assert processedSessionParts.getTotalCount() == totalParts;
1✔
751
    String sha1 = fileHash.digestHash("base64");
1✔
752
    String digest = String.join("", "sha=", sha1);
1✔
753
    Files committedSession =
1✔
754
        this.createFileUploadSessionCommitByUrl(
1✔
755
            commitUrl,
756
            new CreateFileUploadSessionCommitByUrlRequestBody(parts),
757
            new CreateFileUploadSessionCommitByUrlHeaders(digest));
758
    return committedSession.getEntries().get(0);
1✔
759
  }
760

761
  public Authentication getAuth() {
762
    return auth;
×
763
  }
764

765
  public NetworkSession getNetworkSession() {
766
    return networkSession;
×
767
  }
768

769
  public static class Builder {
770

771
    protected Authentication auth;
772

773
    protected NetworkSession networkSession;
774

775
    public Builder() {
1✔
776
      this.networkSession = new NetworkSession();
1✔
777
    }
1✔
778

779
    public Builder auth(Authentication auth) {
780
      this.auth = auth;
1✔
781
      return this;
1✔
782
    }
783

784
    public Builder networkSession(NetworkSession networkSession) {
785
      this.networkSession = networkSession;
1✔
786
      return this;
1✔
787
    }
788

789
    public ChunkedUploadsManager build() {
790
      return new ChunkedUploadsManager(this);
1✔
791
    }
792
  }
793
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc