BUG-47: more subobject models
[bgpcep.git] / pcep / impl / src / main / java / org / opendaylight / protocol / pcep / impl / subobject / EROPathKeyWith128PCEIDSubobjectParser.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.pcep.impl.subobject;
9
10 import java.util.Arrays;
11
12 import org.opendaylight.protocol.pcep.PCEPDeserializerException;
13 import org.opendaylight.protocol.pcep.subobject.EROPathKeyWith128PCEIDSubobject;
14 import org.opendaylight.protocol.util.ByteArray;
15
16 public class EROPathKeyWith128PCEIDSubobjectParser {
17
18     public static final int PK_F_LENGTH = 2;
19     public static final int PCE_ID_F_LENGTH = 16;
20
21     public static final int PK_F_OFFSET = 0;
22     public static final int PCE_ID_F_OFFSET = PK_F_OFFSET + PK_F_LENGTH;
23
24     public static final int CONTENT_LENGTH = PCE_ID_F_OFFSET + PCE_ID_F_LENGTH;
25
26     public static EROPathKeyWith128PCEIDSubobject parse(byte[] soContentsBytes, boolean loose) throws PCEPDeserializerException {
27         if (soContentsBytes == null || soContentsBytes.length == 0)
28             throw new IllegalArgumentException("Array of bytes is mandatory. Can't be null or empty.");
29         if (soContentsBytes.length != CONTENT_LENGTH)
30             throw new PCEPDeserializerException("Wrong length of array of bytes. Passed: " + soContentsBytes.length + "; Expected: >" + CONTENT_LENGTH + ".");
31
32         final int pathKey = ByteArray.bytesToShort(Arrays.copyOfRange(soContentsBytes, PK_F_OFFSET, PCE_ID_F_OFFSET)) & 0xFFFF;
33
34         final byte[] pceId = Arrays.copyOfRange(soContentsBytes, PCE_ID_F_OFFSET, CONTENT_LENGTH);
35
36         return new EROPathKeyWith128PCEIDSubobject(pathKey, pceId, loose);
37     }
38
39     public static byte[] put(EROPathKeyWith128PCEIDSubobject objToSerialize) {
40         final byte[] retBytes = new byte[CONTENT_LENGTH];
41
42         System.arraycopy(ByteArray.shortToBytes((short) objToSerialize.getPathKey()), 0, retBytes, PK_F_OFFSET, PK_F_LENGTH);
43
44         if (objToSerialize.getPceId().length != PCE_ID_F_LENGTH)
45             throw new IllegalArgumentException("Wrong length of pce id. Passed: " + objToSerialize.getPceId().length + ". Expected: =" + PCE_ID_F_LENGTH);
46         System.arraycopy(objToSerialize.getPceId(), 0, retBytes, PCE_ID_F_OFFSET, PCE_ID_F_LENGTH);
47
48         return retBytes;
49     }
50 }