2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.util.messages;
11 import java.nio.ByteBuffer;
13 import com.google.common.base.Charsets;
14 import com.google.common.base.Preconditions;
17 * Netconf message header is used only when chunked framing mechanism is
18 * supported. The header consists of only the length field.
21 public final class NetconfMessageHeader {
23 private static final byte[] HEADER_START = new byte[] { (byte) 0x0a, (byte) 0x23 };
24 private static final byte HEADER_END = (byte) 0x0a;
25 private final long length;
27 public NetconfMessageHeader(final long length) {
28 Preconditions.checkArgument(length < Integer.MAX_VALUE && length > 0);
32 public byte[] toBytes() {
33 return toBytes(this.length);
36 // FIXME: improve precision to long
37 public int getLength() {
38 return (int) this.length;
41 public static NetconfMessageHeader fromBytes(final byte[] bytes) {
42 // the length is variable therefore bytes between headerBegin and
43 // headerEnd mark the length
44 // the length should be only numbers and therefore easily parsed with
46 long length = Long.parseLong(Charsets.US_ASCII.decode(
47 ByteBuffer.wrap(bytes, HEADER_START.length, bytes.length - HEADER_START.length - 1)).toString());
49 return new NetconfMessageHeader(length);
52 public static byte[] toBytes(final long length) {
53 final byte[] l = String.valueOf(length).getBytes(Charsets.US_ASCII);
54 final byte[] h = new byte[HEADER_START.length + l.length + 1];
55 System.arraycopy(HEADER_START, 0, h, 0, HEADER_START.length);
56 System.arraycopy(l, 0, h, HEADER_START.length, l.length);
57 System.arraycopy(new byte[] { HEADER_END }, 0, h, HEADER_START.length + l.length, 1);