Skip to content
This repository was archived by the owner on Dec 4, 2023. It is now read-only.

Commit 13b647a

Browse files
authored
Fixed some 15.handling-attachments leaks (#1049)
1 parent b16bdec commit 13b647a

File tree

1 file changed

+17
-8
lines changed
  • samples/15.handling-attachments/src/main/java/com/microsoft/bot/sample/attachments

1 file changed

+17
-8
lines changed

samples/15.handling-attachments/src/main/java/com/microsoft/bot/sample/attachments/AttachmentsBot.java

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,9 @@ private CompletableFuture<Activity> handleOutgoingAttachment(TurnContext turnCon
153153
private Activity handleIncomingAttachment(Activity activity) {
154154
String replyText = "";
155155
for (Attachment file : activity.getAttachments()) {
156+
ReadableByteChannel remoteChannel = null;
157+
FileOutputStream fos = null;
158+
156159
try {
157160
// Determine where the file is hosted.
158161
URL remoteFileUrl = new URL(file.getContentUrl());
@@ -161,12 +164,18 @@ private Activity handleIncomingAttachment(Activity activity) {
161164
String localFileName = file.getName();
162165

163166
// Download the actual attachment
164-
ReadableByteChannel remoteChannel = Channels.newChannel(remoteFileUrl.openStream());
165-
FileOutputStream fos = new FileOutputStream(localFileName);
166-
167+
remoteChannel = Channels.newChannel(remoteFileUrl.openStream());
168+
fos = new FileOutputStream(localFileName);
167169
fos.getChannel().transferFrom(remoteChannel, 0, Long.MAX_VALUE);
168170
} catch (Throwable t) {
169171
replyText += "Attachment \"" + file.getName() + "\" failed to download.\r\n";
172+
} finally {
173+
if (remoteChannel != null) {
174+
try {remoteChannel.close(); } catch (Throwable ignored) {};
175+
}
176+
if (fos != null) {
177+
try {fos.close(); } catch (Throwable ignored) {};
178+
}
170179
}
171180
}
172181

@@ -237,10 +246,10 @@ private CompletableFuture<String> getEncodedFileData(String filename) {
237246
}
238247

239248
private CompletableFuture<byte[]> getFileData(String filename) {
240-
return Async.wrapBlock(() -> {
241-
InputStream inputStream = Thread.currentThread().
242-
getContextClassLoader().getResourceAsStream(filename);
243-
return IOUtils.toByteArray(inputStream);
244-
});
249+
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)) {
250+
return CompletableFuture.completedFuture(IOUtils.toByteArray(inputStream));
251+
} catch (Throwable t) {
252+
return Async.completeExceptionally(t);
253+
}
245254
}
246255
}

0 commit comments

Comments
 (0)