Add Bundle and Error (ONF-extension) deserializers
[openflowplugin.git] / extension / openflowplugin-extension-onf / src / test / java / org / opendaylight / openflowplugin / extension / onf / ByteBufUtils.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.openflowplugin.extension.onf;
10
11 import com.google.common.base.Splitter;
12 import com.google.common.collect.Lists;
13 import io.netty.buffer.ByteBuf;
14 import io.netty.buffer.UnpooledByteBufAllocator;
15 import java.util.List;
16 import org.junit.Assert;
17 import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
19
20 /**
21  * Abstract class for common ByteBuf util methods.
22  */
23 public abstract class ByteBufUtils {
24
25     private static final Splitter HEXSTRING_SPLITTER =  Splitter.onPattern("\\s+").omitEmptyStrings();
26     private static final byte[] XID = new byte[] { 0x01, 0x02, 0x03, 0x04 };
27     public static final Long DEFAULT_XID = 0x01020304L;
28
29     public static ByteBuf hexStringToByteBuf(final String hexSrc) {
30         ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
31         out.writeBytes(hexStringToBytes(hexSrc));
32         return out;
33     }
34
35     public static ByteBuf buildBuf(final String hexSrc) {
36         ByteBuf out = UnpooledByteBufAllocator.DEFAULT.buffer();
37         out.writeBytes(XID);
38         out.writeBytes(hexStringToBytes(hexSrc));
39         return out;
40     }
41
42     public static void checkHeaderV13(OfHeader ofHeader) {
43         final Short version = EncodeConstants.OF13_VERSION_ID;
44         Assert.assertEquals("Wrong version", version, ofHeader.getVersion());
45         Assert.assertEquals("Wrong Xid", DEFAULT_XID, ofHeader.getXid());
46     }
47
48     private static byte[] hexStringToBytes(final String hexSrc) {
49         List<String> byteChips = Lists.newArrayList(HEXSTRING_SPLITTER.split(hexSrc));
50         byte[] result = new byte[byteChips.size()];
51         int i = 0;
52         for (String chip : byteChips) {
53             result[i] = (byte) Short.parseShort(chip, 16);
54             i++;
55         }
56         return result;
57     }
58
59 }