Use strict String->byte[] conversion
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / MessageParts.java
index 3db8ca6af093fa74807e7cba74f68353b66831fd..fb21b7f8c2a956d545062e42ef75aa3d1deee04a 100644 (file)
@@ -7,8 +7,11 @@
  */
 package org.opendaylight.netconf.nettyutil.handler;
 
-import static java.nio.charset.StandardCharsets.UTF_8;
-
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
 import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
 
 /**
@@ -16,8 +19,28 @@ import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
  *
  * @author Thomas Pantelis
  */
-interface MessageParts {
-    byte[] END_OF_MESSAGE = NetconfMessageConstants.END_OF_MESSAGE.getBytes(UTF_8);
-    byte[] START_OF_CHUNK = NetconfMessageConstants.START_OF_CHUNK.getBytes(UTF_8);
-    byte[] END_OF_CHUNK = NetconfMessageConstants.END_OF_CHUNK.getBytes(UTF_8);
+final class MessageParts {
+    static final byte[] END_OF_MESSAGE = asciiBytes(NetconfMessageConstants.END_OF_MESSAGE);
+    static final byte[] START_OF_CHUNK = asciiBytes(NetconfMessageConstants.START_OF_CHUNK);
+    static final byte[] END_OF_CHUNK = asciiBytes(NetconfMessageConstants.END_OF_CHUNK);
+
+    private MessageParts() {
+        // Hidden on purpose
+    }
+
+    private static byte[] asciiBytes(final String str) {
+        final ByteBuffer buf;
+        try {
+            buf = StandardCharsets.US_ASCII.newEncoder()
+                .onMalformedInput(CodingErrorAction.REPORT)
+                .onUnmappableCharacter(CodingErrorAction.REPORT)
+                .encode(CharBuffer.wrap(str));
+        } catch (CharacterCodingException e) {
+            throw new ExceptionInInitializerError(e);
+        }
+
+        final byte[] ret = new byte[buf.remaining()];
+        buf.get(ret);
+        return ret;
+    }
 }