Skip to content

Commit

Permalink
httpURLConnection.getErrorStream() can return null so handle it. (#31)
Browse files Browse the repository at this point in the history
Co-authored-by: Enrico Bianchi <enrico.bianchi@gmail.com>
  • Loading branch information
brycechesternewman and henryx authored Apr 25, 2023
1 parent 72eba45 commit cd25b49
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 8 deletions.
36 changes: 28 additions & 8 deletions src/main/java/io/github/jopenlibs/vault/rest/Rest.java
Original file line number Diff line number Diff line change
Expand Up @@ -545,14 +545,7 @@ private byte[] responseBodyBytes(final URLConnection connection) throws RestExce
inputStream = httpURLConnection.getErrorStream();
}
}
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int bytesRead;
final byte[] bytes = new byte[16384];
while ((bytesRead = inputStream.read(bytes, 0, bytes.length)) != -1) {
byteArrayOutputStream.write(bytes, 0, bytesRead);
}
byteArrayOutputStream.flush();
return byteArrayOutputStream.toByteArray();
return handleResponseInputStream(inputStream);
} catch (IOException e) {
return new byte[0];
}
Expand Down Expand Up @@ -586,4 +579,31 @@ private int connectionStatus(final URLConnection connection) throws IOException,
return statusCode;
}

/**
* <p>This method handles the response stream from the connection.</p>
*
* @param inputStream The input stream from the connection.
* @return The body payload, downloaded from the HTTP connection response
*/
protected byte[] handleResponseInputStream(final InputStream inputStream) {
try {
// getErrorStream() can return null so handle it.
if (inputStream != null) {
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

int bytesRead;
final byte[] bytes = new byte[16384];
while ((bytesRead = inputStream.read(bytes, 0, bytes.length)) != -1) {
byteArrayOutputStream.write(bytes, 0, bytesRead);
}

byteArrayOutputStream.flush();
return byteArrayOutputStream.toByteArray();
} else {
return new byte[0];
}
} catch (IOException e) {
return new byte[0];
}
}
}
11 changes: 11 additions & 0 deletions src/test/java/io/github/jopenlibs/vault/rest/GetTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -192,4 +192,15 @@ public void testGet_RetrievesResponseBodyWhenStatusIs418() throws RestException
responseBody.contains("User-Agent"));
}


/**
* <p>Verify that response body does not cause NPE when input stream is null.</p>
*/
@Test
public void test_handleResponseInputStream() {
final Rest rest = new Rest();
final byte[] result = rest.handleResponseInputStream(null);
assertEquals(0, result.length);
}

}

0 comments on commit cd25b49

Please sign in to comment.