Skip to content

Commit 497b786

Browse files
httpURLConnection.getErrorStream() can return null so handle it.
1 parent 72eba45 commit 497b786

File tree

2 files changed

+40
-9
lines changed

2 files changed

+40
-9
lines changed

src/main/java/io/github/jopenlibs/vault/rest/Rest.java

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -545,14 +545,7 @@ private byte[] responseBodyBytes(final URLConnection connection) throws RestExce
545545
inputStream = httpURLConnection.getErrorStream();
546546
}
547547
}
548-
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
549-
int bytesRead;
550-
final byte[] bytes = new byte[16384];
551-
while ((bytesRead = inputStream.read(bytes, 0, bytes.length)) != -1) {
552-
byteArrayOutputStream.write(bytes, 0, bytesRead);
553-
}
554-
byteArrayOutputStream.flush();
555-
return byteArrayOutputStream.toByteArray();
548+
return handleResponseInputStream(inputStream);
556549
} catch (IOException e) {
557550
return new byte[0];
558551
}
@@ -586,4 +579,31 @@ private int connectionStatus(final URLConnection connection) throws IOException,
586579
return statusCode;
587580
}
588581

589-
}
582+
/**
583+
* <p>This method </p>
584+
*
585+
* @param inputStream The input stream from the connection.
586+
* @return The body payload, downloaded from the HTTP connection response
587+
*/
588+
protected byte[] handleResponseInputStream(final InputStream inputStream) {
589+
try {
590+
// getErrorStream() can return null so handle it.
591+
if (inputStream != null) {
592+
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
593+
594+
int bytesRead;
595+
final byte[] bytes = new byte[16384];
596+
while ((bytesRead = inputStream.read(bytes, 0, bytes.length)) != -1) {
597+
byteArrayOutputStream.write(bytes, 0, bytesRead);
598+
}
599+
600+
byteArrayOutputStream.flush();
601+
return byteArrayOutputStream.toByteArray();
602+
} else {
603+
return new byte[0];
604+
}
605+
} catch (IOException e) {
606+
return new byte[0];
607+
}
608+
}
609+
}

src/test/java/io/github/jopenlibs/vault/rest/GetTests.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,4 +192,15 @@ public void testGet_RetrievesResponseBodyWhenStatusIs418() throws RestException
192192
responseBody.contains("User-Agent"));
193193
}
194194

195+
196+
/**
197+
* <p>Verify that response body does not cause NPE when input stream is null.</p>
198+
*/
199+
@Test
200+
public void test_handleResponseInputStream() {
201+
final Rest rest = new Rest();
202+
final byte[] result = rest.handleResponseInputStream(null);
203+
assertEquals(0, result.length);
204+
}
205+
195206
}

0 commit comments

Comments
 (0)