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 org.opendaylight.protocol.util.ByteArray;
15 import java.nio.ByteBuffer;
18 * Netconf message header is used only when chunked framing mechanism is
19 * supported. The header consists of only the length field.
21 public final class NetconfMessageHeader {
26 private static final byte[] headerBegin = new byte[] { (byte) 0x0a, (byte) 0x23 };
28 private static final byte headerEnd = (byte) 0x0a;
30 private boolean parsed = false;
32 public NetconfMessageHeader() {
36 public NetconfMessageHeader fromBytes(final byte[] bytes) {
37 // the length is variable therefore bytes between headerBegin and
38 // headerEnd mark the length
39 // the length should be only numbers and therefore easily parsed with
41 this.length = Long.parseLong(Charsets.US_ASCII.decode(
42 ByteBuffer.wrap(ByteArray.subByte(bytes, headerBegin.length, bytes.length - headerBegin.length - 1)))
44 Preconditions.checkState(this.length < Integer.MAX_VALUE && this.length > 0);
49 public byte[] toBytes() {
50 final byte[] l = String.valueOf(this.length).getBytes(Charsets.US_ASCII);
51 final byte[] h = new byte[headerBegin.length + l.length + 1];
52 System.arraycopy(headerBegin, 0, h, 0, headerBegin.length);
53 System.arraycopy(l, 0, h, headerBegin.length, l.length);
54 System.arraycopy(new byte[] { headerEnd }, 0, h, headerBegin.length + l.length, 1);
58 // FIXME: improve precision to long
59 public int getLength() {
60 return (int) this.length;
63 public void setLength(final int length) {
70 public boolean isParsed() {
78 public void setParsed() {