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

box / box-java-sdk-gen / #265

23 Jun 2025 02:39PM UTC coverage: 34.829% (-0.02%) from 34.849%
#265

Pull #342

github

web-flow
Merge 340f45260 into d895e58e6
Pull Request #342: chore: Update .codegen.json with commit hash of codegen and openapi spec

16196 of 46502 relevant lines covered (34.83%)

0.35 hits per line

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

74.62
/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.io.StringReader;
19
import java.math.BigInteger;
20
import java.nio.file.Files;
21
import java.nio.file.Paths;
22
import java.security.PrivateKey;
23
import java.security.Security;
24
import java.text.SimpleDateFormat;
25
import java.util.Arrays;
26
import java.util.Base64;
27
import java.util.Date;
28
import java.util.HashMap;
29
import java.util.Iterator;
30
import java.util.List;
31
import java.util.Map;
32
import java.util.Objects;
33
import java.util.TimeZone;
34
import java.util.UUID;
35
import java.util.function.BiFunction;
36
import java.util.stream.Collectors;
37
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
38
import org.bouncycastle.jce.provider.BouncyCastleProvider;
39
import org.bouncycastle.openssl.PEMDecryptorProvider;
40
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
41
import org.bouncycastle.openssl.PEMKeyPair;
42
import org.bouncycastle.openssl.PEMParser;
43
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
44
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
45
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
46
import org.bouncycastle.operator.InputDecryptorProvider;
47
import org.bouncycastle.operator.OperatorCreationException;
48
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
49
import org.bouncycastle.pkcs.PKCSException;
50
import org.jose4j.jws.JsonWebSignature;
51
import org.jose4j.jwt.JwtClaims;
52
import org.jose4j.jwt.NumericDate;
53
import org.jose4j.lang.JoseException;
54

55
public class UtilsManager {
×
56
  private static final int BUFFER_SIZE = 8192;
57
  private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
1✔
58
  private static final SimpleDateFormat DATE_TIME_FORMAT =
1✔
59
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
60
  private static final SimpleDateFormat DATE_TIME_FORMAT_WITH_MILLIS =
1✔
61
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
62
  private static final SimpleDateFormat DATE_TIME_FORMAT_WITH_MICROS =
1✔
63
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSX");
64

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

73
  public static <K, V> Entry<K, V> entryOf(K key, V value) {
74
    return Entry.of(key, value);
1✔
75
  }
76

77
  public static <K, V> Map<K, V> mergeMaps(Map<K, V> map1, Map<K, V> map2) {
78
    Map<K, V> mergedMap = new HashMap<>();
1✔
79
    if (map1 != null) {
1✔
80
      mergedMap.putAll(map1);
1✔
81
    }
82
    if (map2 != null) {
1✔
83
      mergedMap.putAll(map2);
1✔
84
    }
85
    return mergedMap;
1✔
86
  }
87

88
  public static Map<String, String> prepareParams(Map<String, String> map) {
89
    map.values().removeIf(Objects::isNull);
1✔
90
    return map;
1✔
91
  }
92

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

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

144
  public static String getUuid() {
145
    return UUID.randomUUID().toString();
1✔
146
  }
147

148
  public static byte[] generateByteBuffer(int size) {
149
    byte[] bytes = new byte[size];
1✔
150
    Arrays.fill(bytes, (byte) 0);
1✔
151
    return bytes;
1✔
152
  }
153

154
  public static InputStream generateByteStream(int size) {
155
    byte[] bytes = generateByteBuffer(size);
1✔
156
    return new ByteArrayInputStream(bytes);
1✔
157
  }
158

159
  public static InputStream generateByteStreamFromBuffer(byte[] buffer) {
160
    return new ByteArrayInputStream(buffer);
1✔
161
  }
162

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

181
    return buffer.toByteArray();
1✔
182
  }
183

184
  public static boolean bufferEquals(byte[] buffer1, byte[] buffer2) {
185
    return Arrays.equals(buffer1, buffer2);
1✔
186
  }
187

188
  public static int bufferLength(byte[] buffer) {
189
    return buffer.length;
1✔
190
  }
191

192
  public static InputStream decodeBase64ByteStream(String value) {
193
    return new ByteArrayInputStream(Base64.getDecoder().decode(value));
1✔
194
  }
195

196
  public static String decodeBase64(String value) {
197
    return new String(Base64.getDecoder().decode(value));
1✔
198
  }
199

200
  public static InputStream stringToByteStream(String value) {
201
    return new ByteArrayInputStream(value.getBytes());
1✔
202
  }
203

204
  public static OutputStream getFileOutputStream(String filePath) {
205
    try {
206
      return new FileOutputStream(filePath);
1✔
207
    } catch (FileNotFoundException e) {
×
208
      throw new RuntimeException(e);
×
209
    }
210
  }
211

212
  public static void closeFileOutputStream(OutputStream outputStream) {
213
    try {
214
      outputStream.close();
1✔
215
    } catch (IOException e) {
×
216
      throw new RuntimeException(e);
×
217
    }
1✔
218
  }
1✔
219

220
  public static byte[] readBufferFromFile(String filePath) {
221
    try {
222
      InputStream inputStream = Files.newInputStream(Paths.get(filePath));
1✔
223
      return readByteStream(inputStream);
1✔
224
    } catch (IOException e) {
×
225
      throw new RuntimeException(e);
×
226
    }
227
  }
228

229
  public static String getEnvVar(String envVar) {
230
    return System.getenv(envVar);
1✔
231
  }
232

233
  public static void delayInSeconds(int seconds) {
234
    try {
235
      Thread.sleep(seconds * 1000L);
1✔
236
    } catch (InterruptedException e) {
×
237
      throw new RuntimeException(e);
×
238
    }
1✔
239
  }
1✔
240

241
  public static String readTextFromFile(String filePath) {
242
    try {
243
      return new String(Files.readAllBytes(Paths.get(filePath)));
×
244
    } catch (IOException e) {
×
245
      throw new RuntimeException(e);
×
246
    }
247
  }
248

249
  public static boolean isBrowser() {
250
    return false;
1✔
251
  }
252

253
  public static long getEpochTimeInSeconds() {
254
    return System.currentTimeMillis() / 1000;
1✔
255
  }
256

257
  public static PrivateKey decryptPrivateKey(String encryptedPrivateKey, String passphrase) {
258
    Security.addProvider(new BouncyCastleProvider());
1✔
259
    PrivateKey decryptedPrivateKey;
260
    try {
261
      PEMParser keyReader = new PEMParser(new StringReader(encryptedPrivateKey));
1✔
262
      Object keyPair = keyReader.readObject();
1✔
263
      keyReader.close();
1✔
264

265
      if (keyPair instanceof PrivateKeyInfo) {
1✔
266
        PrivateKeyInfo keyInfo = (PrivateKeyInfo) keyPair;
×
267
        decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
×
268
      } else if (keyPair instanceof PEMEncryptedKeyPair) {
1✔
269
        JcePEMDecryptorProviderBuilder builder = new JcePEMDecryptorProviderBuilder();
×
270
        PEMDecryptorProvider decryptionProvider = builder.build(passphrase.toCharArray());
×
271
        keyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptionProvider);
×
272
        PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
×
273
        decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
×
274
      } else if (keyPair instanceof PKCS8EncryptedPrivateKeyInfo) {
1✔
275
        InputDecryptorProvider pkcs8Prov =
1✔
276
            new JceOpenSSLPKCS8DecryptorProviderBuilder()
277
                .setProvider("BC")
1✔
278
                .build(passphrase.toCharArray());
1✔
279
        PrivateKeyInfo keyInfo =
1✔
280
            ((PKCS8EncryptedPrivateKeyInfo) keyPair).decryptPrivateKeyInfo(pkcs8Prov);
1✔
281
        decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
1✔
282
      } else {
1✔
283
        PrivateKeyInfo keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
×
284
        decryptedPrivateKey = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo);
×
285
      }
286
    } catch (IOException e) {
×
287
      throw new BoxSDKError("Error parsing private key for Box Developer Edition.", e);
×
288
    } catch (OperatorCreationException e) {
×
289
      throw new BoxSDKError("Error parsing PKCS#8 private key for Box Developer Edition.", e);
×
290
    } catch (PKCSException e) {
×
291
      throw new BoxSDKError("Error parsing PKCS private key for Box Developer Edition.", e);
×
292
    }
1✔
293
    return decryptedPrivateKey;
1✔
294
  }
295

296
  public static String createJwtAssertion(
297
      Map<String, Object> claims, JwtKey jwtKey, JwtSignOptions jwtOptions) {
298
    JwtClaims jwtClaims = new JwtClaims();
1✔
299
    jwtClaims.setIssuer(jwtOptions.getIssuer());
1✔
300
    jwtClaims.setAudience(jwtOptions.getAudience());
1✔
301
    jwtClaims.setExpirationTime(NumericDate.fromSeconds((Long) claims.get("exp")));
1✔
302

303
    jwtClaims.setSubject(jwtOptions.getSubject());
1✔
304
    jwtClaims.setClaim("box_sub_type", claims.get("box_sub_type"));
1✔
305
    jwtClaims.setGeneratedJwtId(64);
1✔
306

307
    JsonWebSignature jws = new JsonWebSignature();
1✔
308
    jws.setPayload(jwtClaims.toJson());
1✔
309
    jws.setKey(decryptPrivateKey(jwtKey.getKey(), jwtKey.getPassphrase()));
1✔
310
    jws.setAlgorithmHeaderValue(jwtOptions.getAlgorithm().getValue());
1✔
311
    jws.setHeader("typ", "JWT");
1✔
312
    if ((jwtOptions.getKeyid() != null) && !jwtOptions.getKeyid().isEmpty()) {
1✔
313
      jws.setHeader("kid", jwtOptions.getKeyid());
1✔
314
    }
315

316
    String assertion;
317

318
    try {
319
      assertion = jws.getCompactSerialization();
1✔
320
    } catch (JoseException e) {
×
321
      throw new BoxSDKError("Error serializing JSON Web Token assertion.", e);
×
322
    }
1✔
323

324
    return assertion;
1✔
325
  }
326

327
  public static JsonNode getValueFromObjectRawData(SerializableObject obj, String key) {
328
    JsonNode value = obj.getRawData();
1✔
329
    for (String k : key.split("\\.")) {
1✔
330
      if (value == null || !value.has(k)) {
1✔
331
        return null;
×
332
      }
333
      value = value.get(k);
1✔
334
    }
335

336
    return value;
1✔
337
  }
338

339
  public static double random(double min, double max) {
340
    return Math.random() * (max - min) + min;
×
341
  }
342

343
  public static String hexToBase64(String hex) {
344
    return Base64.getEncoder().encodeToString(new BigInteger(hex, 16).toByteArray());
1✔
345
  }
346

347
  public static Iterator<InputStream> iterateChunks(
348
      InputStream stream, long chunkSize, long fileSize) {
349
    return new Iterator<InputStream>() {
1✔
350
      private boolean streamIsFinished = false;
1✔
351

352
      @Override
353
      public boolean hasNext() {
354
        return !streamIsFinished;
1✔
355
      }
356

357
      @Override
358
      public InputStream next() {
359
        try {
360
          byte[] buffer = new byte[(int) chunkSize];
1✔
361
          int bytesRead = 0;
1✔
362

363
          while (bytesRead < chunkSize) {
1✔
364
            int read = stream.read(buffer, bytesRead, (int) (chunkSize - bytesRead));
1✔
365
            if (read == -1) {
1✔
366
              // End of stream
367
              streamIsFinished = true;
1✔
368
              break;
1✔
369
            }
370
            bytesRead += read;
1✔
371
          }
1✔
372

373
          if (bytesRead == 0) {
1✔
374
            // No more data to yield
375
            streamIsFinished = true;
×
376
            return null;
×
377
          }
378

379
          // Return the chunk as a ByteArrayInputStream
380
          return new ByteArrayInputStream(buffer, 0, bytesRead);
1✔
381
        } catch (Exception e) {
×
382
          throw new RuntimeException("Error reading from stream", e);
×
383
        }
384
      }
385
    };
386
  }
387

388
  /**
389
   * Reduces an iterator using a reducer function and an initial value.
390
   *
391
   * @param <Accumulator> The type of the accumulator (result)
392
   * @param <T> The type of the items in the iterator
393
   * @param iterator The iterator to process
394
   * @param reducer The reducer function
395
   * @param initialValue The initial value for the accumulator
396
   * @return The accumulated result
397
   */
398
  public static <Accumulator, T> Accumulator reduceIterator(
399
      Iterator<T> iterator,
400
      BiFunction<Accumulator, T, Accumulator> reducer,
401
      Accumulator initialValue) {
402
    Accumulator result = initialValue;
1✔
403

404
    while (iterator.hasNext()) {
1✔
405
      T item = iterator.next();
1✔
406
      result = reducer.apply(result, item);
1✔
407
    }
1✔
408

409
    return result;
1✔
410
  }
411

412
  public static Map<String, String> sanitizeMap(
413
      Map<String, String> dictionary, Map<String, String> keysToSanitize) {
414
    return dictionary.entrySet().stream()
1✔
415
        .collect(
1✔
416
            Collectors.toMap(
1✔
417
                Map.Entry::getKey,
418
                entry ->
419
                    keysToSanitize.containsKey(entry.getKey().toLowerCase())
1✔
420
                        ? JsonManager.sanitizedValue()
×
421
                        : entry.getValue()));
1✔
422
  }
423

424
  public static Date dateTimeFromString(String dateString) {
425
    SimpleDateFormat[] formats = {
1✔
426
      DATE_TIME_FORMAT, DATE_TIME_FORMAT_WITH_MILLIS, DATE_TIME_FORMAT_WITH_MICROS
427
    };
428

429
    for (SimpleDateFormat format : formats) {
1✔
430
      try {
431
        return format.parse(dateString);
1✔
432
      } catch (java.text.ParseException e) {
1✔
433
        // Ignore and try the next format
434
      }
435
    }
436
    return null;
×
437
  }
438

439
  public static String dateTimeToString(Date dateTime) {
440
    DATE_TIME_FORMAT_WITH_MILLIS.setTimeZone(TimeZone.getTimeZone("UTC"));
1✔
441
    return DATE_TIME_FORMAT_WITH_MILLIS.format(dateTime);
1✔
442
  }
443

444
  public static Date dateFromString(String dateString) {
445
    try {
446
      return DATE_FORMAT.parse(dateString);
1✔
447
    } catch (java.text.ParseException e) {
×
448
      return null;
×
449
    }
450
  }
451

452
  public static String dateToString(Date date) {
453
    DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
1✔
454
    return DATE_FORMAT.format(date);
1✔
455
  }
456

457
  public static long dateTimeToEpochSeconds(Date dateTime) {
458
    return dateTime.getTime() / 1000;
×
459
  }
460

461
  public static Date epochSecondsToDateTime(long seconds) {
462
    return new Date(seconds * 1000);
1✔
463
  }
464
}
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