Reuse encoder
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / MessageParts.java
index 3db8ca6af093fa74807e7cba74f68353b66831fd..6802507b2caa1858b5bba7fe32cb2f72a6cd85cf 100644 (file)
@@ -7,17 +7,45 @@
  */
 package org.opendaylight.netconf.nettyutil.handler;
 
-import static java.nio.charset.StandardCharsets.UTF_8;
-
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import org.opendaylight.netconf.util.messages.FramingMechanism;
 
 /**
  * netconf message part constants as bytes.
  *
  * @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;
+    static final byte[] START_OF_CHUNK;
+    static final byte[] END_OF_CHUNK;
+
+    static {
+        final var encoder = StandardCharsets.US_ASCII.newEncoder()
+            .onMalformedInput(CodingErrorAction.REPORT)
+            .onUnmappableCharacter(CodingErrorAction.REPORT);
+
+        try {
+            END_OF_MESSAGE = getBytes(encoder, FramingMechanism.EOM_STR);
+            START_OF_CHUNK = getBytes(encoder, FramingMechanism.CHUNK_START_STR);
+            END_OF_CHUNK = getBytes(encoder, FramingMechanism.CHUNK_END_STR);
+        } catch (CharacterCodingException e) {
+            throw new ExceptionInInitializerError(e);
+        }
+    }
+
+    private MessageParts() {
+        // Hidden on purpose
+    }
+
+    private static byte[] getBytes(final CharsetEncoder encoder, final String str) throws CharacterCodingException {
+        final var buf = encoder.encode(CharBuffer.wrap(str));
+        final var bytes = new byte[buf.remaining()];
+        buf.get(bytes);
+        return bytes;
+    }
 }