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

box / box-java-sdk-gen / #59

08 Apr 2025 12:48PM UTC coverage: 35.205% (+0.01%) from 35.192%
#59

push

github

web-flow
feat: Support sensitive data sanitization in errors (box/box-codegen#695) (#267)

40 of 80 new or added lines in 8 files covered. (50.0%)

7 existing lines in 6 files now uncovered.

15268 of 43369 relevant lines covered (35.2%)

0.35 hits per line

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

72.78
/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
      return ((List<?>) value)
1✔
91
          .stream().map(UtilsManager::convertToString).collect(Collectors.joining(","));
1✔
92
    }
93
    if (value instanceof ArrayNode) {
1✔
94
      return convertToString(new ObjectMapper().convertValue(value, List.class));
1✔
95
    }
96

97
    if (value instanceof JsonNode) {
1✔
98
      return ((JsonNode) value).asText();
1✔
99
    }
100
    return value.toString();
1✔
101
  }
102

103
  public static void writeInputStreamToOutputStream(InputStream input, OutputStream output) {
104
    try {
105
      byte[] buffer = new byte[BUFFER_SIZE];
1✔
106
      int n = input.read(buffer);
1✔
107
      while (n != -1) {
1✔
108
        output.write(buffer, 0, n);
1✔
109
        n = input.read(buffer);
1✔
110
      }
111
    } catch (IOException e) {
×
112
      throw new RuntimeException(e);
×
113
    } finally {
114
      try {
115
        input.close();
1✔
116
        output.close();
1✔
117
      } catch (IOException e) {
×
118
        throw new RuntimeException(e);
×
119
      }
1✔
120
    }
121
  }
1✔
122

123
  public static String getUuid() {
124
    return UUID.randomUUID().toString();
1✔
125
  }
126

127
  public static byte[] generateByteBuffer(int size) {
128
    byte[] bytes = new byte[size];
1✔
129
    Arrays.fill(bytes, (byte) 0);
1✔
130
    return bytes;
1✔
131
  }
132

133
  public static InputStream generateByteStream(int size) {
134
    byte[] bytes = generateByteBuffer(size);
1✔
135
    return new ByteArrayInputStream(bytes);
1✔
136
  }
137

138
  public static InputStream generateByteStreamFromBuffer(byte[] buffer) {
139
    return new ByteArrayInputStream(buffer);
1✔
140
  }
141

142
  public static byte[] readByteStream(InputStream inputStream) {
143
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1✔
144
    byte[] data = new byte[BUFFER_SIZE];
1✔
145
    int bytesRead;
146
    try {
147
      while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
1✔
148
        buffer.write(data, 0, bytesRead);
1✔
149
      }
150
    } catch (IOException e) {
×
151
      throw new RuntimeException(e);
×
152
    } finally {
153
      try {
154
        inputStream.close();
1✔
155
      } catch (IOException e) {
×
156
        throw new RuntimeException(e);
×
157
      }
1✔
158
    }
159

160
    return buffer.toByteArray();
1✔
161
  }
162

163
  public static boolean bufferEquals(byte[] buffer1, byte[] buffer2) {
164
    return Arrays.equals(buffer1, buffer2);
1✔
165
  }
166

167
  public static int bufferLength(byte[] buffer) {
168
    return buffer.length;
1✔
169
  }
170

171
  public static InputStream decodeBase64ByteStream(String value) {
172
    return new ByteArrayInputStream(Base64.getDecoder().decode(value));
1✔
173
  }
174

175
  public static String decodeBase64(String value) {
176
    return new String(Base64.getDecoder().decode(value));
1✔
177
  }
178

179
  public static InputStream stringToByteStream(String value) {
180
    return new ByteArrayInputStream(value.getBytes());
1✔
181
  }
182

183
  public static OutputStream getFileOutputStream(String filePath) {
184
    try {
185
      return new FileOutputStream(filePath);
1✔
186
    } catch (FileNotFoundException e) {
×
187
      throw new RuntimeException(e);
×
188
    }
189
  }
190

191
  public static void closeFileOutputStream(OutputStream outputStream) {
192
    try {
193
      outputStream.close();
1✔
194
    } catch (IOException e) {
×
195
      throw new RuntimeException(e);
×
196
    }
1✔
197
  }
1✔
198

199
  public static byte[] readBufferFromFile(String filePath) {
200
    try {
201
      InputStream inputStream = Files.newInputStream(Paths.get(filePath));
1✔
202
      return readByteStream(inputStream);
1✔
203
    } catch (IOException e) {
×
204
      throw new RuntimeException(e);
×
205
    }
206
  }
207

208
  public static String getEnvVar(String envVar) {
209
    return System.getenv(envVar);
1✔
210
  }
211

212
  public static void delayInSeconds(int seconds) {
213
    try {
214
      Thread.sleep(seconds * 1000L);
1✔
215
    } catch (InterruptedException e) {
×
216
      throw new RuntimeException(e);
×
217
    }
1✔
218
  }
1✔
219

220
  public static String readTextFromFile(String filePath) {
221
    try {
222
      return new String(Files.readAllBytes(Paths.get(filePath)));
×
223
    } catch (IOException e) {
×
224
      throw new RuntimeException(e);
×
225
    }
226
  }
227

228
  public static boolean isBrowser() {
229
    return false;
1✔
230
  }
231

232
  public static long getEpochTimeInSeconds() {
233
    return System.currentTimeMillis() / 1000;
1✔
234
  }
235

236
  public static PrivateKey decryptPrivateKey(String encryptedPrivateKey, String passphrase) {
237
    Security.addProvider(new BouncyCastleProvider());
1✔
238
    PrivateKey decryptedPrivateKey;
239
    try {
240
      PEMParser keyReader = new PEMParser(new StringReader(encryptedPrivateKey));
1✔
241
      Object keyPair = keyReader.readObject();
1✔
242
      keyReader.close();
1✔
243

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

275
  public static String createJwtAssertion(
276
      Map<String, Object> claims, JwtKey jwtKey, JwtSignOptions jwtOptions) {
277
    JwtClaims jwtClaims = new JwtClaims();
1✔
278
    jwtClaims.setIssuer(jwtOptions.getIssuer());
1✔
279
    jwtClaims.setAudience(jwtOptions.getAudience());
1✔
280
    jwtClaims.setExpirationTime(NumericDate.fromSeconds((Long) claims.get("exp")));
1✔
281

282
    jwtClaims.setSubject(jwtOptions.getSubject());
1✔
283
    jwtClaims.setClaim("box_sub_type", claims.get("box_sub_type"));
1✔
284
    jwtClaims.setGeneratedJwtId(64);
1✔
285

286
    JsonWebSignature jws = new JsonWebSignature();
1✔
287
    jws.setPayload(jwtClaims.toJson());
1✔
288
    jws.setKey(decryptPrivateKey(jwtKey.getKey(), jwtKey.getPassphrase()));
1✔
289
    jws.setAlgorithmHeaderValue(jwtOptions.getAlgorithm().getValue());
1✔
290
    jws.setHeader("typ", "JWT");
1✔
291
    if ((jwtOptions.getKeyid() != null) && !jwtOptions.getKeyid().isEmpty()) {
1✔
292
      jws.setHeader("kid", jwtOptions.getKeyid());
1✔
293
    }
294

295
    String assertion;
296

297
    try {
298
      assertion = jws.getCompactSerialization();
1✔
299
    } catch (JoseException e) {
×
300
      throw new BoxSDKError("Error serializing JSON Web Token assertion.", e);
×
301
    }
1✔
302

303
    return assertion;
1✔
304
  }
305

306
  public static JsonNode getValueFromObjectRawData(SerializableObject obj, String key) {
307
    JsonNode value = obj.getRawData();
1✔
308
    for (String k : key.split("\\.")) {
1✔
309
      if (value == null || !value.has(k)) {
1✔
310
        return null;
×
311
      }
312
      value = value.get(k);
1✔
313
    }
314

315
    return value;
1✔
316
  }
317

318
  public static double random(double min, double max) {
319
    return Math.random() * (max - min) + min;
×
320
  }
321

322
  public static String hexToBase64(String hex) {
323
    return Base64.getEncoder().encodeToString(new BigInteger(hex, 16).toByteArray());
1✔
324
  }
325

326
  public static Iterator<InputStream> iterateChunks(
327
      InputStream stream, long chunkSize, long fileSize) {
328
    return new Iterator<InputStream>() {
1✔
329
      private boolean streamIsFinished = false;
1✔
330

331
      @Override
332
      public boolean hasNext() {
333
        return !streamIsFinished;
1✔
334
      }
335

336
      @Override
337
      public InputStream next() {
338
        try {
339
          byte[] buffer = new byte[(int) chunkSize];
1✔
340
          int bytesRead = 0;
1✔
341

342
          while (bytesRead < chunkSize) {
1✔
343
            int read = stream.read(buffer, bytesRead, (int) (chunkSize - bytesRead));
1✔
344
            if (read == -1) {
1✔
345
              // End of stream
346
              streamIsFinished = true;
1✔
347
              break;
1✔
348
            }
349
            bytesRead += read;
1✔
350
          }
1✔
351

352
          if (bytesRead == 0) {
1✔
353
            // No more data to yield
354
            streamIsFinished = true;
×
355
            return null;
×
356
          }
357

358
          // Return the chunk as a ByteArrayInputStream
359
          return new ByteArrayInputStream(buffer, 0, bytesRead);
1✔
360
        } catch (Exception e) {
×
361
          throw new RuntimeException("Error reading from stream", e);
×
362
        }
363
      }
364
    };
365
  }
366

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

383
    while (iterator.hasNext()) {
1✔
384
      T item = iterator.next();
1✔
385
      result = reducer.apply(result, item);
1✔
386
    }
1✔
387

388
    return result;
1✔
389
  }
390

391
  public static Map<String, String> sanitizeMap(
392
      Map<String, String> dictionary, Map<String, String> keysToSanitize) {
NEW
393
    return dictionary.entrySet().stream()
×
NEW
394
        .filter(entry -> keysToSanitize.containsKey(entry.getKey().toLowerCase()))
×
NEW
395
        .collect(Collectors.toMap(Map.Entry::getKey, entry -> JsonManager.sanitizedValue()));
×
396
  }
397
}
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