Fix junit dependencies in poms. Reuse existing from parent,
[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
17 public final class MessageUtil {
18
19         public static final int LENGTH_FIELD_LENGTH = 2; // bytes
20         public static final int MARKER_LENGTH = 16; // bytes
21         public static final int TYPE_FIELD_LENGTH = 1; // bytes
22         public static final int COMMON_HEADER_LENGTH = LENGTH_FIELD_LENGTH + TYPE_FIELD_LENGTH + MARKER_LENGTH;
23
24         private MessageUtil() {
25
26         }
27
28         /**
29          * Serializes this BGP Message header to byte array.
30          * 
31          * @param type message type to be formatted
32          * @param body message body
33          * 
34          * @return byte array representation of this header
35          */
36         public static byte[] formatMessage(final int type, final byte[] body) {
37                 final byte[] retBytes = new byte[COMMON_HEADER_LENGTH + body.length];
38
39                 Arrays.fill(retBytes, 0, MARKER_LENGTH, (byte) 0xff);
40                 System.arraycopy(ByteArray.intToBytes(body.length + COMMON_HEADER_LENGTH),
41                                 Integer.SIZE / Byte.SIZE - LENGTH_FIELD_LENGTH,
42                                 retBytes, MARKER_LENGTH, LENGTH_FIELD_LENGTH);
43
44                 retBytes[MARKER_LENGTH + LENGTH_FIELD_LENGTH] = UnsignedBytes.checkedCast(type);
45                 ByteArray.copyWhole(body, retBytes, COMMON_HEADER_LENGTH);
46
47                 return retBytes;
48         }
49 }