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

box / box-java-sdk-gen / #142

28 May 2025 09:09AM UTC coverage: 35.534% (+0.2%) from 35.312%
#142

Pull #317

github

web-flow
Merge a88c4bc17 into 7ea98521c
Pull Request #317: chore: Update .codegen.json with commit hash of codegen and openapi spec

38 of 77 new or added lines in 15 files covered. (49.35%)

9 existing lines in 9 files now uncovered.

15586 of 43862 relevant lines covered (35.53%)

0.36 hits per line

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

72.02
/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
    mergedMap.putAll(map1);
1✔
80
    mergedMap.putAll(map2);
1✔
81
    return mergedMap;
1✔
82
  }
83

84
  public static Map<String, String> prepareParams(Map<String, String> map) {
85
    map.values().removeIf(Objects::isNull);
1✔
86
    return map;
1✔
87
  }
88

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

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

140
  public static String getUuid() {
141
    return UUID.randomUUID().toString();
1✔
142
  }
143

144
  public static byte[] generateByteBuffer(int size) {
145
    byte[] bytes = new byte[size];
1✔
146
    Arrays.fill(bytes, (byte) 0);
1✔
147
    return bytes;
1✔
148
  }
149

150
  public static InputStream generateByteStream(int size) {
151
    byte[] bytes = generateByteBuffer(size);
1✔
152
    return new ByteArrayInputStream(bytes);
1✔
153
  }
154

155
  public static InputStream generateByteStreamFromBuffer(byte[] buffer) {
156
    return new ByteArrayInputStream(buffer);
1✔
157
  }
158

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

177
    return buffer.toByteArray();
1✔
178
  }
179

180
  public static boolean bufferEquals(byte[] buffer1, byte[] buffer2) {
181
    return Arrays.equals(buffer1, buffer2);
1✔
182
  }
183

184
  public static int bufferLength(byte[] buffer) {
185
    return buffer.length;
1✔
186
  }
187

188
  public static InputStream decodeBase64ByteStream(String value) {
189
    return new ByteArrayInputStream(Base64.getDecoder().decode(value));
1✔
190
  }
191

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

196
  public static InputStream stringToByteStream(String value) {
197
    return new ByteArrayInputStream(value.getBytes());
1✔
198
  }
199

200
  public static OutputStream getFileOutputStream(String filePath) {
201
    try {
202
      return new FileOutputStream(filePath);
1✔
203
    } catch (FileNotFoundException e) {
×
204
      throw new RuntimeException(e);
×
205
    }
206
  }
207

208
  public static void closeFileOutputStream(OutputStream outputStream) {
209
    try {
210
      outputStream.close();
1✔
211
    } catch (IOException e) {
×
212
      throw new RuntimeException(e);
×
213
    }
1✔
214
  }
1✔
215

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

225
  public static String getEnvVar(String envVar) {
226
    return System.getenv(envVar);
1✔
227
  }
228

229
  public static void delayInSeconds(int seconds) {
230
    try {
231
      Thread.sleep(seconds * 1000L);
1✔
232
    } catch (InterruptedException e) {
×
233
      throw new RuntimeException(e);
×
234
    }
1✔
235
  }
1✔
236

237
  public static String readTextFromFile(String filePath) {
238
    try {
239
      return new String(Files.readAllBytes(Paths.get(filePath)));
×
240
    } catch (IOException e) {
×
241
      throw new RuntimeException(e);
×
242
    }
243
  }
244

245
  public static boolean isBrowser() {
246
    return false;
1✔
247
  }
248

249
  public static long getEpochTimeInSeconds() {
250
    return System.currentTimeMillis() / 1000;
1✔
251
  }
252

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

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

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

299
    jwtClaims.setSubject(jwtOptions.getSubject());
1✔
300
    jwtClaims.setClaim("box_sub_type", claims.get("box_sub_type"));
1✔
301
    jwtClaims.setGeneratedJwtId(64);
1✔
302

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

312
    String assertion;
313

314
    try {
315
      assertion = jws.getCompactSerialization();
1✔
316
    } catch (JoseException e) {
×
317
      throw new BoxSDKError("Error serializing JSON Web Token assertion.", e);
×
318
    }
1✔
319

320
    return assertion;
1✔
321
  }
322

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

332
    return value;
1✔
333
  }
334

335
  public static double random(double min, double max) {
336
    return Math.random() * (max - min) + min;
×
337
  }
338

339
  public static String hexToBase64(String hex) {
340
    return Base64.getEncoder().encodeToString(new BigInteger(hex, 16).toByteArray());
1✔
341
  }
342

343
  public static Iterator<InputStream> iterateChunks(
344
      InputStream stream, long chunkSize, long fileSize) {
345
    return new Iterator<InputStream>() {
1✔
346
      private boolean streamIsFinished = false;
1✔
347

348
      @Override
349
      public boolean hasNext() {
350
        return !streamIsFinished;
1✔
351
      }
352

353
      @Override
354
      public InputStream next() {
355
        try {
356
          byte[] buffer = new byte[(int) chunkSize];
1✔
357
          int bytesRead = 0;
1✔
358

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

369
          if (bytesRead == 0) {
1✔
370
            // No more data to yield
371
            streamIsFinished = true;
×
372
            return null;
×
373
          }
374

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

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

400
    while (iterator.hasNext()) {
1✔
401
      T item = iterator.next();
1✔
402
      result = reducer.apply(result, item);
1✔
403
    }
1✔
404

405
    return result;
1✔
406
  }
407

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

420
  public static Date dateTimeFromString(String dateString) {
421
    SimpleDateFormat[] formats = {
1✔
422
      DATE_TIME_FORMAT, DATE_TIME_FORMAT_WITH_MILLIS, DATE_TIME_FORMAT_WITH_MICROS
423
    };
424

425
    for (SimpleDateFormat format : formats) {
1✔
426
      try {
427
        return format.parse(dateString);
1✔
428
      } catch (java.text.ParseException e) {
1✔
429
        // Ignore and try the next format
430
      }
431
    }
NEW
432
    return null;
×
433
  }
434

435
  public static String dateTimeToString(Date dateTime) {
436
    DATE_TIME_FORMAT_WITH_MILLIS.setTimeZone(TimeZone.getTimeZone("UTC"));
1✔
437
    return DATE_TIME_FORMAT_WITH_MILLIS.format(dateTime);
1✔
438
  }
439

440
  public static Date dateFromString(String dateString) {
441
    try {
442
      return DATE_FORMAT.parse(dateString);
1✔
NEW
443
    } catch (java.text.ParseException e) {
×
NEW
444
      return null;
×
445
    }
446
  }
447

448
  public static String dateToString(Date date) {
449
    DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
1✔
450
    return DATE_FORMAT.format(date);
1✔
451
  }
452
}
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