Release the temporary ByteBuf in case of unexpected exception in WebSocketUtil.base64. (#10160)
Motivation: An exception may occur between ByteBuf's allocation and release. So I think it's a good idea to place the release operation in a finally block. Modification: Release the temporary ByteBuf in finally blocks. Result: Avoid ByteBuf leak.
This commit is contained in:
parent
c90acf4766
commit
bdaa935756
@ -96,10 +96,18 @@ final class WebSocketUtil {
|
||||
if (PlatformDependent.javaVersion() >= 8) {
|
||||
return java.util.Base64.getEncoder().encodeToString(data);
|
||||
}
|
||||
String encodedString;
|
||||
ByteBuf encodedData = Unpooled.wrappedBuffer(data);
|
||||
ByteBuf encoded = Base64.encode(encodedData);
|
||||
String encodedString = encoded.toString(CharsetUtil.UTF_8);
|
||||
encoded.release();
|
||||
try {
|
||||
ByteBuf encoded = Base64.encode(encodedData);
|
||||
try {
|
||||
encodedString = encoded.toString(CharsetUtil.UTF_8);
|
||||
} finally {
|
||||
encoded.release();
|
||||
}
|
||||
} finally {
|
||||
encodedData.release();
|
||||
}
|
||||
return encodedString;
|
||||
}
|
||||
|
||||
|
@ -17,6 +17,15 @@ package io.netty.handler.codec.http.websocketx;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.ByteBufUtil;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.handler.codec.base64.Base64;
|
||||
import io.netty.util.CharsetUtil;
|
||||
import io.netty.util.internal.EmptyArrays;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class WebSocketUtilTest {
|
||||
@ -40,4 +49,26 @@ public class WebSocketUtilTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBase64() {
|
||||
String base64 = WebSocketUtil.base64(EmptyArrays.EMPTY_BYTES);
|
||||
assertNotNull(base64);
|
||||
assertTrue(base64.isEmpty());
|
||||
|
||||
base64 = WebSocketUtil.base64("foo".getBytes(CharsetUtil.UTF_8));
|
||||
assertEquals(base64, "Zm9v");
|
||||
|
||||
base64 = WebSocketUtil.base64("bar".getBytes(CharsetUtil.UTF_8));
|
||||
ByteBuf src = Unpooled.wrappedBuffer(base64.getBytes(CharsetUtil.UTF_8));
|
||||
try {
|
||||
ByteBuf dst = Base64.decode(src);
|
||||
try {
|
||||
assertEquals(new String(ByteBufUtil.getBytes(dst), CharsetUtil.UTF_8), "bar");
|
||||
} finally {
|
||||
dst.release();
|
||||
}
|
||||
} finally {
|
||||
src.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user