Netconf message related constants moved to one place.
[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 org.opendaylight.protocol.util.ByteArray;
14
15 import java.nio.ByteBuffer;
16
17 /**
18  * Netconf message header is used only when chunked framing mechanism is
19  * supported. The header consists of only the length field.
20  */
21 public final class NetconfMessageHeader {
22
23     private long length;
24
25     // \n#<length>\n
26     private static final byte[] headerBegin = new byte[] { (byte) 0x0a, (byte) 0x23 };
27
28     private static final byte headerEnd = (byte) 0x0a;
29
30     private boolean parsed = false;
31
32     public NetconfMessageHeader() {
33
34     }
35
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
40         // ASCII
41         this.length = Long.parseLong(Charsets.US_ASCII.decode(
42                 ByteBuffer.wrap(ByteArray.subByte(bytes, headerBegin.length, bytes.length - headerBegin.length - 1)))
43                 .toString());
44         Preconditions.checkState(this.length < Integer.MAX_VALUE && this.length > 0);
45         this.parsed = true;
46         return this;
47     }
48
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);
55         return h;
56     }
57
58     // FIXME: improve precision to long
59     public int getLength() {
60         return (int) this.length;
61     }
62
63     public void setLength(final int length) {
64         this.length = length;
65     }
66
67     /**
68      * @return the parsed
69      */
70     public boolean isParsed() {
71         return this.parsed;
72     }
73
74     /**
75      * @param parsed
76      *            the parsed to set
77      */
78     public void setParsed() {
79         this.parsed = false;
80     }
81 }