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 com.google.common.base.Charsets;
12 import com.google.common.base.Preconditions;
13 import java.nio.ByteBuffer;
16 * Netconf message header is used only when chunked framing mechanism is
17 * supported. The header consists of only the length field.
20 public final class NetconfMessageHeader {
22 private static final byte[] HEADER_START = new byte[] { (byte) 0x0a, (byte) 0x23 };
23 private static final byte HEADER_END = (byte) 0x0a;
24 private final long length;
26 public NetconfMessageHeader(final long length) {
27 Preconditions.checkArgument(length < Integer.MAX_VALUE && length > 0);
31 public byte[] toBytes() {
32 return toBytes(this.length);
35 // FIXME: improve precision to long
36 public int getLength() {
37 return (int) this.length;
40 public static NetconfMessageHeader fromBytes(final byte[] bytes) {
41 // the length is variable therefore bytes between headerBegin and
42 // headerEnd mark the length
43 // the length should be only numbers and therefore easily parsed with
45 long length = Long.parseLong(Charsets.US_ASCII.decode(
46 ByteBuffer.wrap(bytes, HEADER_START.length, bytes.length - HEADER_START.length - 1)).toString());
48 return new NetconfMessageHeader(length);
51 public static byte[] toBytes(final long length) {
52 final byte[] l = String.valueOf(length).getBytes(Charsets.US_ASCII);
53 final byte[] h = new byte[HEADER_START.length + l.length + 1];
54 System.arraycopy(HEADER_START, 0, h, 0, HEADER_START.length);
55 System.arraycopy(l, 0, h, HEADER_START.length, l.length);
56 System.arraycopy(new byte[] { HEADER_END }, 0, h, HEADER_START.length + l.length, 1);