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

box / box-java-sdk / #7740

13 Nov 2026 03:15PM UTC coverage: 33.622% (-0.09%) from 33.708%
#7740

push

github

web-flow
fix: Upgrade Jackson libraries to 2.22.4 (box/box-codegen#1008)

21792 of 64815 relevant lines covered (33.62%)

0.34 hits per line

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

74.57
/src/main/java/com/box/sdkgen/internal/utils/UtilsManager.java
1
package com.box.sdkgen.internal.utils;
2

3
import com.box.sdkgen.box.errors.BoxSDKError;
4
import com.box.sdkgen.internal.SerializableObject;
5
import com.box.sdkgen.serialization.json.EnumWrapper;
6
import com.box.sdkgen.serialization.json.JsonManager;
7
import com.box.sdkgen.serialization.json.Valuable;
8
import com.fasterxml.jackson.databind.JsonNode;
9
import com.fasterxml.jackson.databind.ObjectMapper;
10
import com.fasterxml.jackson.databind.node.ArrayNode;
11
import java.io.ByteArrayInputStream;
12
import java.io.ByteArrayOutputStream;
13
import java.io.FileNotFoundException;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.io.OutputStream;
18
import java.nio.charset.StandardCharsets;
19
import java.nio.file.Files;
20
import java.nio.file.Paths;
21
import java.security.MessageDigest;
22
import java.security.SecureRandom;
23
import java.time.OffsetDateTime;
24
import java.time.ZoneOffset;
25
import java.time.format.DateTimeFormatter;
26
import java.time.format.DateTimeFormatterBuilder;
27
import java.time.format.DateTimeParseException;
28
import java.time.temporal.ChronoField;
29
import java.time.temporal.ChronoUnit;
30
import java.util.Arrays;
31
import java.util.Base64;
32
import java.util.HashMap;
33
import java.util.Iterator;
34
import java.util.List;
35
import java.util.Locale;
36
import java.util.Map;
37
import java.util.NoSuchElementException;
38
import java.util.Objects;
39
import java.util.Set;
40
import java.util.UUID;
41
import java.util.function.BiFunction;
42
import java.util.stream.Collectors;
43
import javax.crypto.Mac;
44
import javax.crypto.spec.SecretKeySpec;
45
import org.apache.commons.codec.DecoderException;
46
import org.apache.commons.codec.binary.Hex;
47
import org.jose4j.jws.JsonWebSignature;
48
import org.jose4j.jwt.JwtClaims;
49
import org.jose4j.jwt.NumericDate;
50
import org.jose4j.lang.JoseException;
51

52
public class UtilsManager {
×
53
  private static final int BUFFER_SIZE = 8192;
54

55
  private static final DateTimeFormatter OFFSET_DATE_TIME_FORMAT =
1 ✔
56
      new DateTimeFormatterBuilder()
57
          .appendPattern("yyyy-MM-dd'T'HH:mm:ss")
1 ✔
58
          .optionalStart()
1 ✔
59
          .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
1 ✔
60
          .optionalEnd()
1 ✔
61
          .appendOffsetId()
1 ✔
62
          .toFormatter();
1 ✔
63
  private static final DateTimeFormatter OFFSET_DATE_FORMAT =
1 ✔
64
      DateTimeFormatter.ofPattern("yyyy-MM-dd");
1 ✔
65

66
  public static <K, V> Map<K, V> mapOf(Entry<K, V>... entries) {
67
    return Arrays.stream(entries)
1 ✔
68
        .collect(
1 ✔
69
            HashMap::new,
70
            (map, entry) -> map.put(entry.getKey(), entry.getValue()),
1 ✔
71
            HashMap::putAll);
72
  }
73

74
  public static <V> Set<V> setOf(V... values) {
75
    return Arrays.stream(values).collect(Collectors.toSet());
×
76
  }
77

78
  public static <K, V> Entry<K, V> entryOf(K key, V value) {
79
    return Entry.of(key, value);
1 ✔
80
  }
81

82
  public static <K, V> Map<K, V> mergeMaps(Map<K, V> map1, Map<K, V> map2) {
83
    Map<K, V> mergedMap = new HashMap<>();
1 ✔
84
    if (map1 != null) {
1 ✔
85
      mergedMap.putAll(map1);
1 ✔
86
    }
87
    if (map2 != null) {
1 ✔
88
      mergedMap.putAll(map2);
1 ✔
89
    }
90
    return mergedMap;
1 ✔
91
  }
92

93
  public static Map<String, String> prepareParams(Map<String, String> map) {
94
    map.values().removeIf(Objects::isNull);
1 ✔
95
    return map;
1 ✔
96
  }
97

98
  public static String convertToString(Object value) {
99
    if (value == null) {
1 ✔
100
      return null;
1 ✔
101
    }
102
    if (value instanceof EnumWrapper) {
1 ✔
103
      return ((EnumWrapper<?>) value).getStringValue();
1 ✔
104
    }
105
    if (value instanceof Valuable) {
1 ✔
106
      return ((Valuable) value).getValue();
1 ✔
107
    }
108
    if (value instanceof List) {
1 ✔
109
      List<?> list = (List<?>) value;
1 ✔
110
      if (!list.isEmpty() && list.get(0) instanceof SerializableObject) {
1 ✔
111
        return JsonManager.serialize(value).toString();
1 ✔
112
      } else {
113
        return ((List<?>) value)
1 ✔
114
            .stream().map(UtilsManager::convertToString).collect(Collectors.joining(","));
1 ✔
115
      }
116
    }
117
    if (value instanceof ArrayNode) {
1 ✔
118
      return convertToString(new ObjectMapper().convertValue(value, List.class));
×
119
    }
120
    if (value instanceof JsonNode) {
1 ✔
121
      return ((JsonNode) value).asText();
×
122
    }
123
    if (value instanceof SerializableObject) {
1 ✔
124
      return JsonManager.serialize(value).toString();
×
125
    }
126
    return value.toString();
1 ✔
127
  }
128

129
  public static void writeInputStreamToOutputStream(InputStream input, OutputStream output) {
130
    try {
131
      byte[] buffer = new byte[BUFFER_SIZE];
1 ✔
132
      int n = input.read(buffer);
1 ✔
133
      while (n != -1) {
1 ✔
134
        output.write(buffer, 0, n);
1 ✔
135
        n = input.read(buffer);
1 ✔
136
      }
137
    } catch (IOException e) {
×
138
      throw new RuntimeException(e);
×
139
    } finally {
140
      try {
141
        input.close();
1 ✔
142
        output.close();
1 ✔
143
      } catch (IOException e) {
×
144
        throw new RuntimeException(e);
×
145
      }
1 ✔
146
    }
147
  }
1 ✔
148

149
  public static String getUuid() {
150
    return UUID.randomUUID().toString();
1 ✔
151
  }
152

153
  public static byte[] generateByteBuffer(int size) {
154
    byte[] bytes = new byte[size];
1 ✔
155
    new SecureRandom().nextBytes(bytes);
1 ✔
156
    return bytes;
1 ✔
157
  }
158

159
  public static InputStream generateByteStream(int size) {
160
    byte[] bytes = generateByteBuffer(size);
1 ✔
161
    return new ByteArrayInputStream(bytes);
1 ✔
162
  }
163

164
  public static InputStream generateByteStreamFromBuffer(byte[] buffer) {
165
    return new ByteArrayInputStream(buffer);
1 ✔
166
  }
167

168
  public static byte[] readByteStream(InputStream inputStream) {
169
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1 ✔
170
    byte[] data = new byte[BUFFER_SIZE];
1 ✔
171
    int bytesRead;
172
    try {
173
      while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
1 ✔
174
        buffer.write(data, 0, bytesRead);
1 ✔
175
      }
176
    } catch (IOException e) {
×
177
      throw new RuntimeException(e);
×
178
    } finally {
179
      try {
180
        inputStream.close();
1 ✔
181
      } catch (IOException e) {
×
182
        throw new RuntimeException(e);
×
183
      }
1 ✔
184
    }
185

186
    return buffer.toByteArray();
1 ✔
187
  }
188

189
  public static boolean bufferEquals(byte[] buffer1, byte[] buffer2) {
190
    return Arrays.equals(buffer1, buffer2);
1 ✔
191
  }
192

193
  public static int bufferLength(byte[] buffer) {
194
    return buffer.length;
1 ✔
195
  }
196

197
  public static InputStream decodeBase64ByteStream(String value) {
198
    return new ByteArrayInputStream(Base64.getDecoder().decode(value));
1 ✔
199
  }
200

201
  public static String decodeBase64(String value) {
202
    return new String(Base64.getDecoder().decode(value));
1 ✔
203
  }
204

205
  public static InputStream stringToByteStream(String value) {
206
    return new ByteArrayInputStream(value.getBytes());
1 ✔
207
  }
208

209
  public static OutputStream getFileOutputStream(String filePath) {
210
    try {
211
      return new FileOutputStream(filePath);
1 ✔
212
    } catch (FileNotFoundException e) {
×
213
      throw new RuntimeException(e);
×
214
    }
215
  }
216

217
  public static void closeFileOutputStream(OutputStream outputStream) {
218
    try {
219
      outputStream.close();
1 ✔
220
    } catch (IOException e) {
×
221
      throw new RuntimeException(e);
×
222
    }
1 ✔
223
  }
1 ✔
224

225
  public static byte[] readBufferFromFile(String filePath) {
226
    try {
227
      InputStream inputStream = Files.newInputStream(Paths.get(filePath));
1 ✔
228
      return readByteStream(inputStream);
1 ✔
229
    } catch (IOException e) {
×
230
      throw new RuntimeException(e);
×
231
    }
232
  }
233

234
  public static String getEnvVar(String envVar) {
235
    return System.getenv(envVar);
1 ✔
236
  }
237

238
  public static void delayInSeconds(int seconds) {
239
    try {
240
      Thread.sleep(seconds * 1000L);
1 ✔
241
    } catch (InterruptedException e) {
×
242
      throw new RuntimeException(e);
×
243
    }
1 ✔
244
  }
1 ✔
245

246
  public static String readTextFromFile(String filePath) {
247
    try {
248
      return new String(Files.readAllBytes(Paths.get(filePath)));
×
249
    } catch (IOException e) {
×
250
      throw new RuntimeException(e);
×
251
    }
252
  }
253

254
  public static boolean isBrowser() {
255
    return false;
1 ✔
256
  }
257

258
  public static long getEpochTimeInSeconds() {
259
    return System.currentTimeMillis() / 1000;
1 ✔
260
  }
261

262
  public static String createJwtAssertion(
263
      Map<String, Object> claims, JwtKey jwtKey, JwtSignOptions jwtOptions) {
264
    JwtClaims jwtClaims = new JwtClaims();
1 ✔
265
    jwtClaims.setIssuer(jwtOptions.getIssuer());
1 ✔
266
    jwtClaims.setAudience(jwtOptions.getAudience());
1 ✔
267
    jwtClaims.setExpirationTime(NumericDate.fromSeconds((Long) claims.get("exp")));
1 ✔
268

269
    jwtClaims.setSubject(jwtOptions.getSubject());
1 ✔
270
    jwtClaims.setClaim("box_sub_type", claims.get("box_sub_type"));
1 ✔
271
    jwtClaims.setGeneratedJwtId(64);
1 ✔
272

273
    JsonWebSignature jws = new JsonWebSignature();
1 ✔
274
    jws.setPayload(jwtClaims.toJson());
1 ✔
275
    jws.setKey(
1 ✔
276
        jwtOptions.privateKeyDecryptor.decryptPrivateKey(jwtKey.getKey(), jwtKey.getPassphrase()));
1 ✔
277
    jws.setAlgorithmHeaderValue(jwtOptions.getAlgorithm().getValue());
1 ✔
278
    jws.setHeader("typ", "JWT");
1 ✔
279
    if ((jwtOptions.getKeyid() != null) && !jwtOptions.getKeyid().isEmpty()) {
1 ✔
280
      jws.setHeader("kid", jwtOptions.getKeyid());
1 ✔
281
    }
282

283
    String assertion;
284

285
    try {
286
      assertion = jws.getCompactSerialization();
1 ✔
287
    } catch (JoseException e) {
×
288
      throw new BoxSDKError("Error serializing JSON Web Token assertion.", e);
×
289
    }
1 ✔
290

291
    return assertion;
1 ✔
292
  }
293

294
  public static JsonNode getValueFromObjectRawData(SerializableObject obj, String key) {
295
    JsonNode value = obj.getRawData();
×
296
    for (String k : key.split("\\.")) {
×
297
      if (value == null || !value.has(k)) {
×
298
        return null;
×
299
      }
300
      value = value.get(k);
×
301
    }
302

303
    return value;
×
304
  }
305

306
  public static double random(double min, double max) {
307
    return Math.random() * (max - min) + min;
1 ✔
308
  }
309

310
  public static String hexToBase64(String hex) {
311
    try {
312
      return Base64.getEncoder().encodeToString(Hex.decodeHex(hex));
1 ✔
313
    } catch (DecoderException e) {
×
314
      throw new BoxSDKError("Error decoding hex string.", e);
×
315
    }
316
  }
317

318
  public static Iterator<InputStream> iterateChunks(
319
      InputStream stream, long chunkSize, long fileSize) {
320
    return new Iterator<InputStream>() {
1 ✔
321
      private InputStream nextChunk;
322
      private boolean isNextChunkPrepared = false;
1 ✔
323

324
      private void prepareNext() {
325
        if (isNextChunkPrepared) {
1 ✔
326
          return;
1 ✔
327
        }
328
        isNextChunkPrepared = true;
1 ✔
329
        try {
330
          byte[] buffer = new byte[(int) chunkSize];
1 ✔
331
          int bytesRead = 0;
1 ✔
332

333
          while (bytesRead < chunkSize) {
1 ✔
334
            int read = stream.read(buffer, bytesRead, (int) (chunkSize - bytesRead));
1 ✔
335
            if (read == -1) {
1 ✔
336
              break;
1 ✔
337
            }
338
            bytesRead += read;
1 ✔
339
          }
1 ✔
340

341
          if (bytesRead == 0) {
1 ✔
342
            nextChunk = null;
1 ✔
343
            return;
1 ✔
344
          }
345

346
          nextChunk = new ByteArrayInputStream(buffer, 0, bytesRead);
1 ✔
347
        } catch (IOException e) {
×
348
          throw new RuntimeException("Error reading from stream", e);
×
349
        }
1 ✔
350
      }
1 ✔
351

352
      @Override
353
      public boolean hasNext() {
354
        prepareNext();
1 ✔
355
        return nextChunk != null;
1 ✔
356
      }
357

358
      @Override
359
      public InputStream next() {
360
        prepareNext();
1 ✔
361
        if (nextChunk == null) {
1 ✔
362
          throw new NoSuchElementException();
×
363
        }
364
        InputStream result = nextChunk;
1 ✔
365
        nextChunk = null;
1 ✔
366
        isNextChunkPrepared = false;
1 ✔
367
        return result;
1 ✔
368
      }
369
    };
370
  }
371

372
  /**
373
   * Reduces an iterator using a reducer function and an initial value.
374
   *
375
   * @param <Accumulator> The type of the accumulator (result)
376
   * @param <T> The type of the items in the iterator
377
   * @param iterator The iterator to process
378
   * @param reducer The reducer function
379
   * @param initialValue The initial value for the accumulator
380
   * @return The accumulated result
381
   */
382
  public static <Accumulator, T> Accumulator reduceIterator(
383
      Iterator<T> iterator,
384
      BiFunction<Accumulator, T, Accumulator> reducer,
385
      Accumulator initialValue) {
386
    Accumulator result = initialValue;
1 ✔
387

388
    while (iterator.hasNext()) {
1 ✔
389
      T item = iterator.next();
1 ✔
390
      result = reducer.apply(result, item);
1 ✔
391
    }
1 ✔
392

393
    return result;
1 ✔
394
  }
395

396
  public static Map<String, String> sanitizeMap(
397
      Map<String, String> dictionary, Map<String, String> keysToSanitize) {
398
    return dictionary.entrySet().stream()
×
399
        .collect(
×
400
            Collectors.toMap(
×
401
                Map.Entry::getKey,
402
                entry ->
403
                    keysToSanitize.containsKey(entry.getKey().toLowerCase(Locale.ROOT))
×
404
                        ? JsonManager.sanitizedValue()
×
405
                        : entry.getValue()));
×
406
  }
407

408
  public static OffsetDateTime dateTimeFromString(String dateString) {
409
    try {
410
      return OffsetDateTime.parse(dateString, OFFSET_DATE_TIME_FORMAT);
1 ✔
411
    } catch (DateTimeParseException e) {
×
412
      return null;
×
413
    }
414
  }
415

416
  public static String dateTimeToString(OffsetDateTime dateTime) {
417
    return dateTime.truncatedTo(ChronoUnit.SECONDS).format(OFFSET_DATE_TIME_FORMAT);
1 ✔
418
  }
419

420
  public static OffsetDateTime dateFromString(String dateString) {
421
    try {
422
      // For date-only strings, parse as date and convert to OffsetDateTime at start of day UTC
423
      if (dateString.matches("\\d{4}-\\d{2}-\\d{2}")) {
1 ✔
424
        return OffsetDateTime.parse(dateString + "T00:00:00Z");
1 ✔
425
      }
426
      // Otherwise try to parse as full OffsetDateTime
427
      return dateTimeFromString(dateString);
×
428
    } catch (DateTimeParseException e) {
×
429
      return null;
×
430
    }
431
  }
432

433
  public static String dateToString(OffsetDateTime date) {
434
    return date.format(OFFSET_DATE_FORMAT);
1 ✔
435
  }
436

437
  public static String escapeUnicode(String value) {
438
    if (value == null) {
1 ✔
439
      return null;
×
440
    }
441

442
    StringBuilder result = new StringBuilder();
1 ✔
443
    for (int i = 0; i < value.length(); i++) {
1 ✔
444
      char ch = value.charAt(i);
1 ✔
445
      if (ch >= 0x007F) {
1 ✔
446
        result.append(String.format("\\u%04x", (int) ch));
1 ✔
447
      } else if (ch == '\\') {
1 ✔
448
        result.append("\\\\");
1 ✔
449
      } else if (ch == '\n') {
1 ✔
450
        result.append("\\n");
×
451
      } else if (ch == '\r') {
1 ✔
452
        result.append("\\r");
1 ✔
453
      } else if (ch == '\t') {
1 ✔
454
        result.append("\\t");
×
455
      } else if (ch == '/') {
1 ✔
456
        if (i == 0 || value.charAt(i - 1) != '\\') {
1 ✔
457
          result.append("\\/");
1 ✔
458
        } else {
459
          result.append(ch);
×
460
        }
461
      } else {
462
        result.append(ch);
1 ✔
463
      }
464
    }
465
    return result.toString();
1 ✔
466
  }
467

468
  public static OffsetDateTime epochSecondsToDateTime(long seconds) {
469
    return OffsetDateTime.ofInstant(java.time.Instant.ofEpochSecond(seconds), ZoneOffset.UTC);
1 ✔
470
  }
471

472
  public static long dateTimeToEpochSeconds(OffsetDateTime dateTime) {
473
    return dateTime.toEpochSecond();
1 ✔
474
  }
475

476
  public static boolean compareSignatures(String expectedSignature, String receivedSignature) {
477
    if (expectedSignature == null || receivedSignature == null) {
1 ✔
478
      return false;
×
479
    }
480
    byte[] expectedBytes = expectedSignature.getBytes(StandardCharsets.UTF_8);
1 ✔
481
    byte[] receivedBytes = receivedSignature.getBytes(StandardCharsets.UTF_8);
1 ✔
482
    return MessageDigest.isEqual(expectedBytes, receivedBytes);
1 ✔
483
  }
484

485
  public static String computeWebhookSignature(
486
      String body, Map<String, String> headers, String signatureKey, boolean escapeBody) {
487
    if (signatureKey == null) {
1 ✔
488
      return null;
×
489
    }
490
    if (!"1".equals(headers.get("box-signature-version"))) {
1 ✔
491
      return null;
×
492
    }
493
    if (!"HmacSHA256".equals(headers.get("box-signature-algorithm"))) {
1 ✔
494
      return null;
×
495
    }
496
    if (!headers.containsKey("box-delivery-timestamp")) {
1 ✔
497
      return null;
×
498
    }
499

500
    try {
501
      String escapedBody = escapeBody ? escapeUnicode(body) : body;
1 ✔
502
      byte[] encodedSignatureKey = signatureKey.getBytes("UTF-8");
1 ✔
503
      byte[] encodedBody = escapedBody.getBytes("UTF-8");
1 ✔
504
      byte[] encodedTimestamp = headers.get("box-delivery-timestamp").getBytes("UTF-8");
1 ✔
505
      Mac mac = Mac.getInstance("HmacSHA256");
1 ✔
506
      SecretKeySpec secretKeySpec = new SecretKeySpec(encodedSignatureKey, "HmacSHA256");
1 ✔
507
      mac.init(secretKeySpec);
1 ✔
508
      mac.update(encodedBody);
1 ✔
509
      mac.update(encodedTimestamp);
1 ✔
510
      byte[] hmacDigest = mac.doFinal();
1 ✔
511
      return Base64.getEncoder().encodeToString(hmacDigest);
1 ✔
512
    } catch (Exception e) {
×
513
      return null;
×
514
    }
515
  }
516
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc