Remove netconf from commons/opendaylight pom
[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 com.google.common.base.Charsets;
12 import com.google.common.base.Preconditions;
13 import java.nio.ByteBuffer;
14
15 /**
16  * Netconf message header is used only when chunked framing mechanism is
17  * supported. The header consists of only the length field.
18  */
19 @Deprecated
20 public final class NetconfMessageHeader {
21     // \n#<length>\n
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;
25
26     public NetconfMessageHeader(final long length) {
27         Preconditions.checkArgument(length < Integer.MAX_VALUE && length > 0);
28         this.length = length;
29     }
30
31     public byte[] toBytes() {
32         return toBytes(this.length);
33     }
34
35     // FIXME: improve precision to long
36     public int getLength() {
37         return (int) this.length;
38     }
39
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
44         // ASCII
45         long length = Long.parseLong(Charsets.US_ASCII.decode(
46                 ByteBuffer.wrap(bytes, HEADER_START.length, bytes.length - HEADER_START.length - 1)).toString());
47
48         return new NetconfMessageHeader(length);
49     }
50
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);
57         return h;
58     }
59 }