Close the FileChannel in case of an IOException in AbstractDiskHttpData.addContent. (#10188)

Motivation:

`FileChannel.force` may throw an IOException. A fd leak may happen here.

Modification:

Close the fileChannel in a finally block.

Result:

Avoid fd leak.
This commit is contained in:
feijermu 2020-04-15 15:24:26 +08:00 committed by Norman Maurer
parent 25607c0d83
commit a4ad6d15cd
2 changed files with 42 additions and 2 deletions

View File

@ -182,8 +182,11 @@ public abstract class AbstractDiskHttpData extends AbstractHttpData {
RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
fileChannel = accessFile.getChannel();
}
fileChannel.force(false);
fileChannel.close();
try {
fileChannel.force(false);
} finally {
fileChannel.close();
}
fileChannel = null;
setCompleted();
} else {

View File

@ -16,11 +16,15 @@
package io.netty.handler.codec.http.multipart;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@ -93,4 +97,37 @@ public class DiskFileUploadTest {
assertEquals(2, f.getFile().length());
f.delete();
}
@Test
public void testAddContents() throws Exception {
DiskFileUpload f1 = new DiskFileUpload("file1", "file1", "application/json", null, null, 0);
try {
String json = "{\"foo\":\"bar\"}";
byte[] bytes = json.getBytes(CharsetUtil.UTF_8);
f1.addContent(Unpooled.wrappedBuffer(bytes), true);
assertEquals(json, f1.getString());
assertArrayEquals(bytes, f1.get());
File file = f1.getFile();
assertEquals((long) bytes.length, file.length());
FileInputStream fis = new FileInputStream(file);
try {
byte[] buf = new byte[bytes.length];
int offset = 0;
int read = 0;
int len = buf.length;
while ((read = fis.read(buf, offset, len)) > 0) {
len -= read;
offset += read;
if (len <= 0 || offset >= buf.length) {
break;
}
}
assertArrayEquals(bytes, buf);
} finally {
fis.close();
}
} finally {
f1.delete();
}
}
}