diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketUtil.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketUtil.java index fbd43eb261..8699f6412c 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketUtil.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketUtil.java @@ -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; } diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketUtilTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketUtilTest.java index e40501951a..bbaf35c61a 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketUtilTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketUtilTest.java @@ -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(); + } + } }