Skip to content

Commit

Permalink
httpURLConnection.getErrorStream() can return null so handle it.
Browse files Browse the repository at this point in the history
  • Loading branch information
brycechesternewman committed Apr 24, 2023
1 parent 8b9fcfa commit d65c09e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 12 deletions.
41 changes: 29 additions & 12 deletions src/main/java/io/github/jopenlibs/vault/rest/Rest.java
Original file line number Diff line number Diff line change
Expand Up @@ -545,17 +545,7 @@ private byte[] responseBodyBytes(final URLConnection connection) throws RestExce
inputStream = httpURLConnection.getErrorStream();
}
}
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// getErrorStream() can return null so handle it.
if(inputStream != null) {
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 @@ -589,4 +579,31 @@ private int connectionStatus(final URLConnection connection) throws IOException,
return statusCode;
}

}
/**
* <p>This method </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 d65c09e

Please sign in to comment.