BUG-49 : added tests & removed warnings: bgp-parser-spi
[bgpcep.git] / bgp / parser-spi / src / main / java / org / opendaylight / protocol / bgp / parser / spi / MessageUtil.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 package org.opendaylight.protocol.bgp.parser.spi;
9
10 import java.util.Arrays;
11
12 import org.opendaylight.protocol.util.ByteArray;
13
14 import com.google.common.primitives.UnsignedBytes;
15
16 public final class MessageUtil {
17
18         public static final int LENGTH_FIELD_LENGTH = 2;
19         public static final int MARKER_LENGTH = 16;
20         public static final int TYPE_FIELD_LENGTH = 1;
21         public static final int COMMON_HEADER_LENGTH = LENGTH_FIELD_LENGTH + TYPE_FIELD_LENGTH + MARKER_LENGTH;
22
23         private MessageUtil() {
24
25         }
26
27         /**
28          * Serializes this BGP Message header to byte array.
29          * 
30          * @param type message type to be formatted
31          * @param body message body
32          * 
33          * @return byte array representation of this header
34          */
35         public static byte[] formatMessage(final int type, final byte[] body) {
36                 final byte[] retBytes = new byte[COMMON_HEADER_LENGTH + body.length];
37
38                 Arrays.fill(retBytes, 0, MARKER_LENGTH, UnsignedBytes.MAX_VALUE);
39                 System.arraycopy(ByteArray.intToBytes(body.length + COMMON_HEADER_LENGTH), Integer.SIZE / Byte.SIZE - LENGTH_FIELD_LENGTH,
40                                 retBytes, MARKER_LENGTH, LENGTH_FIELD_LENGTH);
41
42                 retBytes[MARKER_LENGTH + LENGTH_FIELD_LENGTH] = UnsignedBytes.checkedCast(type);
43                 ByteArray.copyWhole(body, retBytes, COMMON_HEADER_LENGTH);
44
45                 return retBytes;
46         }
47 }