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

box / box-java-sdk-gen / #286

24 Jun 2025 01:09PM UTC coverage: 35.631% (-0.001%) from 35.632%
#286

push

github

web-flow
fix: Fix Locale Comparison for upperCase and lowerCase (box/box-codegen#746) (#345)

1 of 4 new or added lines in 4 files covered. (25.0%)

3 existing lines in 3 files now uncovered.

16569 of 46502 relevant lines covered (35.63%)

0.36 hits per line

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

72.08
/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.Locale;
32
import java.util.Map;
33
import java.util.Objects;
34
import java.util.TimeZone;
35
import java.util.UUID;
36
import java.util.function.BiFunction;
37
import java.util.stream.Collectors;
38
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
39
import org.bouncycastle.jce.provider.BouncyCastleProvider;
40
import org.bouncycastle.openssl.PEMDecryptorProvider;
41
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
42
import org.bouncycastle.openssl.PEMKeyPair;
43
import org.bouncycastle.openssl.PEMParser;
44
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
45
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
46
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
47
import org.bouncycastle.operator.InputDecryptorProvider;
48
import org.bouncycastle.operator.OperatorCreationException;
49
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
50
import org.bouncycastle.pkcs.PKCSException;
51
import org.jose4j.jws.JsonWebSignature;
52
import org.jose4j.jwt.JwtClaims;
53
import org.jose4j.jwt.NumericDate;
54
import org.jose4j.lang.JoseException;
55

56
public class UtilsManager {
×
57
  private static final int BUFFER_SIZE = 8192;
58
  private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
1✔
59
  private static final SimpleDateFormat DATE_TIME_FORMAT =
1✔
60
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
61
  private static final SimpleDateFormat DATE_TIME_FORMAT_WITH_MILLIS =
1✔
62
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
63
  private static final SimpleDateFormat DATE_TIME_FORMAT_WITH_MICROS =
1✔
64
      new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSX");
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 <K, V> Entry<K, V> entryOf(K key, V value) {
75
    return Entry.of(key, value);
1✔
76
  }
77

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

317
    String assertion;
318

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

325
    return assertion;
1✔
326
  }
327

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

337
    return value;
1✔
338
  }
339

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

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

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

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

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

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

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

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

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

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

410
    return result;
1✔
411
  }
412

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

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

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

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

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

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

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

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