Remove dependecies on bgpcep concepts/util
[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
14 import java.nio.ByteBuffer;
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 public final class NetconfMessageHeader {
21
22     private long length;
23
24     // \n#<length>\n
25     private static final byte[] headerBegin = new byte[] { (byte) 0x0a, (byte) 0x23 };
26
27     private static final byte headerEnd = (byte) 0x0a;
28
29     private boolean parsed = false;
30
31     public NetconfMessageHeader() {
32
33     }
34
35     public NetconfMessageHeader fromBytes(final byte[] bytes) {
36         // the length is variable therefore bytes between headerBegin and
37         // headerEnd mark the length
38         // the length should be only numbers and therefore easily parsed with
39         // ASCII
40         this.length = Long.parseLong(Charsets.US_ASCII.decode(
41                 ByteBuffer.wrap(bytes, headerBegin.length, bytes.length - headerBegin.length - 1)).toString());
42         Preconditions.checkState(this.length < Integer.MAX_VALUE && this.length > 0);
43         this.parsed = true;
44         return this;
45     }
46
47     public byte[] toBytes() {
48         final byte[] l = String.valueOf(this.length).getBytes(Charsets.US_ASCII);
49         final byte[] h = new byte[headerBegin.length + l.length + 1];
50         System.arraycopy(headerBegin, 0, h, 0, headerBegin.length);
51         System.arraycopy(l, 0, h, headerBegin.length, l.length);
52         System.arraycopy(new byte[] { headerEnd }, 0, h, headerBegin.length + l.length, 1);
53         return h;
54     }
55
56     // FIXME: improve precision to long
57     public int getLength() {
58         return (int) this.length;
59     }
60
61     public void setLength(final int length) {
62         this.length = length;
63     }
64
65     /**
66      * @return the parsed
67      */
68     public boolean isParsed() {
69         return this.parsed;
70     }
71
72     /**
73      * @param parsed
74      *            the parsed to set
75      */
76     public void setParsed() {
77         this.parsed = false;
78     }
79 }