Refactor DOMDataBrokerImpl
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / messages / NetconfMessageHeader.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. 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
9 package org.opendaylight.controller.netconf.util.messages;
10
11 import java.nio.ByteBuffer;
12
13 import com.google.common.base.Charsets;
14 import com.google.common.base.Preconditions;
15
16 /**
17  * Netconf message header is used only when chunked framing mechanism is
18  * supported. The header consists of only the length field.
19  */
20 @Deprecated
21 public final class NetconfMessageHeader {
22     // \n#<length>\n
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;
26
27     public NetconfMessageHeader(final long length) {
28         Preconditions.checkArgument(length < Integer.MAX_VALUE && length > 0);
29         this.length = length;
30     }
31
32     public byte[] toBytes() {
33         return toBytes(this.length);
34     }
35
36     // FIXME: improve precision to long
37     public int getLength() {
38         return (int) this.length;
39     }
40
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
45         // ASCII
46         long length = Long.parseLong(Charsets.US_ASCII.decode(
47                 ByteBuffer.wrap(bytes, HEADER_START.length, bytes.length - HEADER_START.length - 1)).toString());
48
49         return new NetconfMessageHeader(length);
50     }
51
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);
58         return h;
59     }
60 }