2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.pcep.impl.subobject;
10 import org.opendaylight.protocol.util.ByteArray;
11 import org.opendaylight.protocol.concepts.IPv4Address;
12 import org.opendaylight.protocol.concepts.IPv4Prefix;
13 import org.opendaylight.protocol.concepts.Prefix;
14 import org.opendaylight.protocol.pcep.PCEPDeserializerException;
15 import org.opendaylight.protocol.pcep.subobject.EROIPPrefixSubobject;
16 import org.opendaylight.protocol.pcep.subobject.ExplicitRouteSubobject;
17 import com.google.common.primitives.UnsignedBytes;
20 * Parser for {@link org.opendaylight.protocol.pcep.subobject.EROIPPrefixSubobject
21 * EROIPPrefixSubobject<IPv4Prefix>}
23 public class EROIPv4PrefixSubobjectParser {
24 public static final int IP_F_LENGTH = 4;
25 public static final int PREFIX_F_LENGTH = 1;
27 public static final int IP_F_OFFSET = 0;
28 public static final int PREFIX_F_OFFSET = IP_F_OFFSET + IP_F_LENGTH;
30 public static final int CONTENT_LENGTH = PREFIX_F_OFFSET + PREFIX_F_LENGTH + 1; //added reserved field of size 1 byte
32 public static EROIPPrefixSubobject<IPv4Prefix> parse(byte[] soContentsBytes, boolean loose) throws PCEPDeserializerException {
33 if (soContentsBytes == null || soContentsBytes.length == 0)
34 throw new IllegalArgumentException("Array of bytes is mandatory. Can't be null or empty.");
35 if (soContentsBytes.length != CONTENT_LENGTH)
36 throw new PCEPDeserializerException("Wrong length of array of bytes. Passed: " + soContentsBytes.length + "; Expected: " + CONTENT_LENGTH + ".");
38 final IPv4Address address = new IPv4Address(ByteArray.subByte(soContentsBytes, IP_F_OFFSET, IP_F_LENGTH));
39 final int length = UnsignedBytes.toInt(soContentsBytes[PREFIX_F_OFFSET]);
41 return new EROIPPrefixSubobject<IPv4Prefix>(new IPv4Prefix(address, length), loose);
44 public static byte[] put(ExplicitRouteSubobject objToSerialize) {
45 if (!(objToSerialize instanceof EROIPPrefixSubobject))
46 throw new IllegalArgumentException("Unknown ExplicitRouteSubobject instance. Passed " + objToSerialize.getClass()
47 + ". Needed EROIPPrefixSubobject.");
49 final EROIPPrefixSubobject<?> specObj = (EROIPPrefixSubobject<?>) objToSerialize;
50 final Prefix<?> prefix = specObj.getPrefix();
52 if (!(prefix instanceof IPv4Prefix))
53 throw new IllegalArgumentException("Unknown AbstractPrefix instance. Passed " + prefix.getClass() + ". Needed IPv4Prefix.");
55 final byte[] retBytes = new byte[CONTENT_LENGTH];
56 ByteArray.copyWhole(prefix.getAddress().getAddress(), retBytes, IP_F_OFFSET);
57 retBytes[PREFIX_F_OFFSET] = ByteArray.intToBytes(prefix.getLength())[Integer.SIZE / Byte.SIZE - 1];