fb21b7f8c2a956d545062e42ef75aa3d1deee04a
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / MessageParts.java
1 /*
2  * Copyright (c) 2018 Inocybe Technologies and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netconf.nettyutil.handler;
9
10 import java.nio.ByteBuffer;
11 import java.nio.CharBuffer;
12 import java.nio.charset.CharacterCodingException;
13 import java.nio.charset.CodingErrorAction;
14 import java.nio.charset.StandardCharsets;
15 import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
16
17 /**
18  * netconf message part constants as bytes.
19  *
20  * @author Thomas Pantelis
21  */
22 final class MessageParts {
23     static final byte[] END_OF_MESSAGE = asciiBytes(NetconfMessageConstants.END_OF_MESSAGE);
24     static final byte[] START_OF_CHUNK = asciiBytes(NetconfMessageConstants.START_OF_CHUNK);
25     static final byte[] END_OF_CHUNK = asciiBytes(NetconfMessageConstants.END_OF_CHUNK);
26
27     private MessageParts() {
28         // Hidden on purpose
29     }
30
31     private static byte[] asciiBytes(final String str) {
32         final ByteBuffer buf;
33         try {
34             buf = StandardCharsets.US_ASCII.newEncoder()
35                 .onMalformedInput(CodingErrorAction.REPORT)
36                 .onUnmappableCharacter(CodingErrorAction.REPORT)
37                 .encode(CharBuffer.wrap(str));
38         } catch (CharacterCodingException e) {
39             throw new ExceptionInInitializerError(e);
40         }
41
42         final byte[] ret = new byte[buf.remaining()];
43         buf.get(ret);
44         return ret;
45     }
46 }