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

box / box-java-sdk-gen / #96

09 May 2025 01:16PM UTC coverage: 35.312% (+0.1%) from 35.204%
#96

push

github

web-flow
fix: Fix conversion of `mdfilters` into query parameters (box/box-codegen#721) (#301)

5 of 7 new or added lines in 1 file covered. (71.43%)

287 existing lines in 27 files now uncovered.

15468 of 43804 relevant lines covered (35.31%)

0.35 hits per line

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

71.19
/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.util.Arrays;
25
import java.util.Base64;
26
import java.util.HashMap;
27
import java.util.Iterator;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.Objects;
31
import java.util.UUID;
32
import java.util.function.BiFunction;
33
import java.util.stream.Collectors;
34
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
35
import org.bouncycastle.jce.provider.BouncyCastleProvider;
36
import org.bouncycastle.openssl.PEMDecryptorProvider;
37
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
38
import org.bouncycastle.openssl.PEMKeyPair;
39
import org.bouncycastle.openssl.PEMParser;
40
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
41
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
42
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
43
import org.bouncycastle.operator.InputDecryptorProvider;
44
import org.bouncycastle.operator.OperatorCreationException;
45
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
46
import org.bouncycastle.pkcs.PKCSException;
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
  public static <K, V> Map<K, V> mapOf(Entry<K, V>... entries) {
56
    return Arrays.stream(entries)
1✔
57
        .collect(
1✔
58
            HashMap::new,
59
            (map, entry) -> map.put(entry.getKey(), entry.getValue()),
1✔
60
            HashMap::putAll);
61
  }
62

63
  public static <K, V> Entry<K, V> entryOf(K key, V value) {
64
    return Entry.of(key, value);
1✔
65
  }
66

67
  public static <K, V> Map<K, V> mergeMaps(Map<K, V> map1, Map<K, V> map2) {
68
    Map<K, V> mergedMap = new HashMap<>();
1✔
69
    mergedMap.putAll(map1);
1✔
70
    mergedMap.putAll(map2);
1✔
71
    return mergedMap;
1✔
72
  }
73

74
  public static Map<String, String> prepareParams(Map<String, String> map) {
75
    map.values().removeIf(Objects::isNull);
1✔
76
    return map;
1✔
77
  }
78

79
  public static String convertToString(Object value) {
80
    if (value == null) {
1✔
81
      return null;
1✔
82
    }
83
    if (value instanceof EnumWrapper) {
1✔
84
      return ((EnumWrapper<?>) value).getStringValue();
1✔
85
    }
86
    if (value instanceof Valuable) {
1✔
87
      return ((Valuable) value).getValue();
1✔
88
    }
89
    if (value instanceof List) {
1✔
90
      List<?> list = (List<?>) value;
1✔
91
      if (!list.isEmpty() && list.get(0) instanceof SerializableObject) {
1✔
NEW
92
        return JsonManager.serialize(value).toString();
×
93
      } else {
94
        return ((List<?>) value)
1✔
95
            .stream().map(UtilsManager::convertToString).collect(Collectors.joining(","));
1✔
96
      }
97
    }
98
    if (value instanceof ArrayNode) {
1✔
99
      return convertToString(new ObjectMapper().convertValue(value, List.class));
1✔
100
    }
101
    if (value instanceof JsonNode) {
1✔
102
      return ((JsonNode) value).asText();
1✔
103
    }
104
    if (value instanceof SerializableObject) {
1✔
NEW
105
      return JsonManager.serialize(value).toString();
×
106
    }
107
    return value.toString();
1✔
108
  }
109

110
  public static void writeInputStreamToOutputStream(InputStream input, OutputStream output) {
111
    try {
112
      byte[] buffer = new byte[BUFFER_SIZE];
1✔
113
      int n = input.read(buffer);
1✔
114
      while (n != -1) {
1✔
115
        output.write(buffer, 0, n);
1✔
116
        n = input.read(buffer);
1✔
117
      }
118
    } catch (IOException e) {
×
119
      throw new RuntimeException(e);
×
120
    } finally {
121
      try {
122
        input.close();
1✔
123
        output.close();
1✔
124
      } catch (IOException e) {
×
125
        throw new RuntimeException(e);
×
126
      }
1✔
127
    }
128
  }
1✔
129

130
  public static String getUuid() {
131
    return UUID.randomUUID().toString();
1✔
132
  }
133

134
  public static byte[] generateByteBuffer(int size) {
135
    byte[] bytes = new byte[size];
1✔
136
    Arrays.fill(bytes, (byte) 0);
1✔
137
    return bytes;
1✔
138
  }
139

140
  public static InputStream generateByteStream(int size) {
141
    byte[] bytes = generateByteBuffer(size);
1✔
142
    return new ByteArrayInputStream(bytes);
1✔
143
  }
144

145
  public static InputStream generateByteStreamFromBuffer(byte[] buffer) {
146
    return new ByteArrayInputStream(buffer);
1✔
147
  }
148

149
  public static byte[] readByteStream(InputStream inputStream) {
150
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1✔
151
    byte[] data = new byte[BUFFER_SIZE];
1✔
152
    int bytesRead;
153
    try {
154
      while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
1✔
155
        buffer.write(data, 0, bytesRead);
1✔
156
      }
157
    } catch (IOException e) {
×
158
      throw new RuntimeException(e);
×
159
    } finally {
160
      try {
161
        inputStream.close();
1✔
162
      } catch (IOException e) {
×
163
        throw new RuntimeException(e);
×
164
      }
1✔
165
    }
166

167
    return buffer.toByteArray();
1✔
168
  }
169

170
  public static boolean bufferEquals(byte[] buffer1, byte[] buffer2) {
171
    return Arrays.equals(buffer1, buffer2);
1✔
172
  }
173

174
  public static int bufferLength(byte[] buffer) {
175
    return buffer.length;
1✔
176
  }
177

178
  public static InputStream decodeBase64ByteStream(String value) {
179
    return new ByteArrayInputStream(Base64.getDecoder().decode(value));
1✔
180
  }
181

182
  public static String decodeBase64(String value) {
183
    return new String(Base64.getDecoder().decode(value));
1✔
184
  }
185

186
  public static InputStream stringToByteStream(String value) {
187
    return new ByteArrayInputStream(value.getBytes());
1✔
188
  }
189

190
  public static OutputStream getFileOutputStream(String filePath) {
191
    try {
192
      return new FileOutputStream(filePath);
1✔
193
    } catch (FileNotFoundException e) {
×
194
      throw new RuntimeException(e);
×
195
    }
196
  }
197

198
  public static void closeFileOutputStream(OutputStream outputStream) {
199
    try {
200
      outputStream.close();
1✔
201
    } catch (IOException e) {
×
202
      throw new RuntimeException(e);
×
203
    }
1✔
204
  }
1✔
205

206
  public static byte[] readBufferFromFile(String filePath) {
207
    try {
208
      InputStream inputStream = Files.newInputStream(Paths.get(filePath));
1✔
209
      return readByteStream(inputStream);
1✔
210
    } catch (IOException e) {
×
211
      throw new RuntimeException(e);
×
212
    }
213
  }
214

215
  public static String getEnvVar(String envVar) {
216
    return System.getenv(envVar);
1✔
217
  }
218

219
  public static void delayInSeconds(int seconds) {
220
    try {
221
      Thread.sleep(seconds * 1000L);
1✔
222
    } catch (InterruptedException e) {
×
223
      throw new RuntimeException(e);
×
224
    }
1✔
225
  }
1✔
226

227
  public static String readTextFromFile(String filePath) {
228
    try {
229
      return new String(Files.readAllBytes(Paths.get(filePath)));
×
230
    } catch (IOException e) {
×
231
      throw new RuntimeException(e);
×
232
    }
233
  }
234

235
  public static boolean isBrowser() {
236
    return false;
1✔
237
  }
238

239
  public static long getEpochTimeInSeconds() {
240
    return System.currentTimeMillis() / 1000;
1✔
241
  }
242

243
  public static PrivateKey decryptPrivateKey(String encryptedPrivateKey, String passphrase) {
244
    Security.addProvider(new BouncyCastleProvider());
1✔
245
    PrivateKey decryptedPrivateKey;
246
    try {
247
      PEMParser keyReader = new PEMParser(new StringReader(encryptedPrivateKey));
1✔
248
      Object keyPair = keyReader.readObject();
1✔
249
      keyReader.close();
1✔
250

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

282
  public static String createJwtAssertion(
283
      Map<String, Object> claims, JwtKey jwtKey, JwtSignOptions jwtOptions) {
284
    JwtClaims jwtClaims = new JwtClaims();
1✔
285
    jwtClaims.setIssuer(jwtOptions.getIssuer());
1✔
286
    jwtClaims.setAudience(jwtOptions.getAudience());
1✔
287
    jwtClaims.setExpirationTime(NumericDate.fromSeconds((Long) claims.get("exp")));
1✔
288

289
    jwtClaims.setSubject(jwtOptions.getSubject());
1✔
290
    jwtClaims.setClaim("box_sub_type", claims.get("box_sub_type"));
1✔
291
    jwtClaims.setGeneratedJwtId(64);
1✔
292

293
    JsonWebSignature jws = new JsonWebSignature();
1✔
294
    jws.setPayload(jwtClaims.toJson());
1✔
295
    jws.setKey(decryptPrivateKey(jwtKey.getKey(), jwtKey.getPassphrase()));
1✔
296
    jws.setAlgorithmHeaderValue(jwtOptions.getAlgorithm().getValue());
1✔
297
    jws.setHeader("typ", "JWT");
1✔
298
    if ((jwtOptions.getKeyid() != null) && !jwtOptions.getKeyid().isEmpty()) {
1✔
299
      jws.setHeader("kid", jwtOptions.getKeyid());
1✔
300
    }
301

302
    String assertion;
303

304
    try {
305
      assertion = jws.getCompactSerialization();
1✔
306
    } catch (JoseException e) {
×
307
      throw new BoxSDKError("Error serializing JSON Web Token assertion.", e);
×
308
    }
1✔
309

310
    return assertion;
1✔
311
  }
312

313
  public static JsonNode getValueFromObjectRawData(SerializableObject obj, String key) {
314
    JsonNode value = obj.getRawData();
1✔
315
    for (String k : key.split("\\.")) {
1✔
316
      if (value == null || !value.has(k)) {
1✔
317
        return null;
×
318
      }
319
      value = value.get(k);
1✔
320
    }
321

322
    return value;
1✔
323
  }
324

325
  public static double random(double min, double max) {
326
    return Math.random() * (max - min) + min;
×
327
  }
328

329
  public static String hexToBase64(String hex) {
330
    return Base64.getEncoder().encodeToString(new BigInteger(hex, 16).toByteArray());
1✔
331
  }
332

333
  public static Iterator<InputStream> iterateChunks(
334
      InputStream stream, long chunkSize, long fileSize) {
335
    return new Iterator<InputStream>() {
1✔
336
      private boolean streamIsFinished = false;
1✔
337

338
      @Override
339
      public boolean hasNext() {
340
        return !streamIsFinished;
1✔
341
      }
342

343
      @Override
344
      public InputStream next() {
345
        try {
346
          byte[] buffer = new byte[(int) chunkSize];
1✔
347
          int bytesRead = 0;
1✔
348

349
          while (bytesRead < chunkSize) {
1✔
350
            int read = stream.read(buffer, bytesRead, (int) (chunkSize - bytesRead));
1✔
351
            if (read == -1) {
1✔
352
              // End of stream
353
              streamIsFinished = true;
1✔
354
              break;
1✔
355
            }
356
            bytesRead += read;
1✔
357
          }
1✔
358

359
          if (bytesRead == 0) {
1✔
360
            // No more data to yield
361
            streamIsFinished = true;
×
362
            return null;
×
363
          }
364

365
          // Return the chunk as a ByteArrayInputStream
366
          return new ByteArrayInputStream(buffer, 0, bytesRead);
1✔
367
        } catch (Exception e) {
×
368
          throw new RuntimeException("Error reading from stream", e);
×
369
        }
370
      }
371
    };
372
  }
373

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

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

395
    return result;
1✔
396
  }
397

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