Skip to content

Commit c781984

Browse files
committed
Close the response body in the case of error.
1 parent 73c866c commit c781984

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

examples/src/main/java/io/kubernetes/client/examples/WatchExample.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,12 @@ public static void main(String[] args) throws IOException, ApiException {
3939
null, null, null, null, null, 5, null, null, Boolean.TRUE, null, null),
4040
new TypeToken<Watch.Response<V1Namespace>>() {}.getType());
4141

42-
for (Watch.Response<V1Namespace> item : watch) {
43-
System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName());
42+
try {
43+
for (Watch.Response<V1Namespace> item : watch) {
44+
System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName());
45+
}
46+
} finally {
47+
watch.close();
4448
}
4549
}
4650
}

util/src/main/java/io/kubernetes/client/util/Watch.java

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@
3232
* CoreV1Api.listNamespaceCall and set watch to True and watch the changes to namespaces.
3333
*/
3434
public class Watch<T>
35-
implements Iterable<Watch.Response<T>>, Iterator<Watch.Response<T>>, java.io.Closeable {
35+
implements Iterable<Watch.Response<T>>,
36+
Iterator<Watch.Response<T>>,
37+
java.io.Closeable,
38+
AutoCloseable {
3639

3740
/**
3841
* Response class holds a watch response that has a `type` that can be ADDED, MODIFIED, DELETED
@@ -82,13 +85,13 @@ public static <T> Watch<T> createWatch(ApiClient client, Call call, Type watchTy
8285
com.squareup.okhttp.Response response = call.execute();
8386
if (!response.isSuccessful()) {
8487
String respBody = null;
85-
if (response.body() != null) {
86-
try {
88+
try (ResponseBody body = response.body()) {
89+
if (body != null) {
8790
respBody = response.body().string();
88-
} catch (IOException e) {
89-
throw new ApiException(
90-
response.message(), e, response.code(), response.headers().toMultimap());
9191
}
92+
} catch (IOException e) {
93+
throw new ApiException(
94+
response.message(), e, response.code(), response.headers().toMultimap());
9295
}
9396
throw new ApiException(
9497
response.message(), response.code(), response.headers().toMultimap(), respBody);

0 commit comments

Comments
 (0)